Java 从 HashSet 数组中按索引获取一个项目,同时显示列表中每个项目的平均长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26185802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 01:59:25  来源:igfitidea点击:

Get an item by index from the HashSet array and also display the average length of each item in the list

javaarrays

提问by user3078406

Hi I have created code that uses a HashSet array. I am brand new to Java programming and I would like to know how to accomplish these two tasks:

嗨,我创建了使用 HashSet 数组的代码。我是 Java 编程的新手,我想知道如何完成这两个任务:

*Get an item by index from the HashSet array *display the average length of each item in the list

*通过索引从HashSet数组中获取一个项目 *显示列表中每个项目的平均长度

My code isn't long at all so I am pasting the entire code here. Thanks for all your help.

我的代码一点也不长,所以我把整个代码贴在这里。感谢你的帮助。

public class MainActivity extends Activity {

Button aButton; // Global Scope
Button sButton;
TextView text2;
EditText eText;
HashSet<String> list = new HashSet<String>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.new_layout); 

    aButton = (Button) this.findViewById(R.id.button1);
    text2 = (TextView) this.findViewById(R.id.textView1);

    //Clickable Saved Input will display alert
    text2.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Complete!", Toast.LENGTH_LONG).show();

        }
    });

    aButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


            list.add("Books");
            list.add("Newspapers");
            list.add("Magazines");
            String listString = "";

            for (String s : list) {
                listString += s + " - ";
            }
            text2.setText(listString);
            }
        });




    sButton = (Button) this.findViewById(R.id.button2);
    eText = (EditText) this.findViewById(R.id.editText1);

    sButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {


             //Log.v("EditText", eText.getText().toString());
            if( !list.add(eText.getText().toString()) )
            {
                System.out.println("Not Unique Item");
                Toast.makeText(getApplicationContext(), "Already Saved!", Toast.LENGTH_LONG).show();
            } else 
            {
                System.out.println("Unique Entry Added");
                Toast.makeText(getApplicationContext(), "Saved To Items.", Toast.LENGTH_LONG).show();

            }


        }

    });


    }

}

采纳答案by Bohemian

A Set is not what you want, because:

Set 不是你想要的,因为:

  • Sets only hold uniquevalues
  • The elements of a Set have no order, so you can't access elements by index
  • 集合只保存唯一
  • Set 的元素没有顺序,所以你不能通过索引访问元素

A better choice is a List, such as an ArrayList, which allows any (ie duplicate) values and can be accessed by index using list.get(i).

一个更好的选择是一个 List,例如 an ArrayList,它允许任何(即重复的)值并且可以使用list.get(i).

回答by Moni

HashSet should be used when you don't want to allow duplicate value in your collection. In HashSet you won't be able to find value by index. If you still want to find the element you have no other option but to use the iterator, it will iterate through the Hashset and give you one by one element from the Hashset.

当您不想在集合中允许重复值时,应使用 HashSet。在 HashSet 中,您将无法通过索引找到值。如果您仍然想找到元素,您别无选择,只能使用迭代器,它将遍历 Hashset 并从 Hashset 中一一为您提供元素。

You want to find your element by index you should use ArrayList.

你想通过索引找到你的元素,你应该使用 ArrayList。

There are two ways of iterating the HashSet -

有两种迭代 HashSet 的方法 -

HashSet <String> newset = new HashSet <String>();

 // populate hash set
      newset.add("A"); 
      newset.add("BB");
      newset.add("CCC");  

      // create an iterator
      Iterator iterator = newset.iterator(); 

      // check values
      while (iterator.hasNext()){
         System.out.println("Value: "+iterator.next() + " ");  
      }

Second approach is by using for loop-

第二种方法是使用 for 循环 -

for (String s : newset ) {
    System.out.println("Value: " +s);
}