从HashSet数组中按索引获取项目,并在列表中显示每个项目的平均长度 [英] Get an item by index from the HashSet array and also display the average length of each item in the list
问题描述
我创建了使用HashSet数组的代码。我是Java编程的新手,我想知道如何完成这两个任务:
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数组
中按索引获取项目*显示列表中每个项目的平均长度
*Get an item by index from the HashSet array *display the average length of each item in the list
我的代码根本不长,所以我将整个代码粘贴到这里。
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();
}
}
});
}
}
推荐答案
集合不是您想要的,因为:
A Set is not what you want, because:
- 集合仅容纳唯一值
- 集合中的元素没有顺序,因此您无法按索引访问元素
一个更好的选择是列表,例如 ArrayList
,它允许任何(即重复)值,并且可以通过使用<$ c的索引进行访问$ c> list.get(i)。
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)
.
这篇关于从HashSet数组中按索引获取项目,并在列表中显示每个项目的平均长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!