我想在我的程序中创建另一个类的对象的列表。我希望能够访问列表中的特定对象,然后使用该对象从类中获取数据。这里是我的课从我创建的对象:如何正确创建对象列表,然后按索引使用这些对象?
public class objectdata extends Activity {
int number=0;
String word="";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
}
public objectdata(int num, String word){
number = num;
word = word;
}
}
这里就是对象添加到列表中的类,并在那里我希望访问对象:
public class MainActivity extends Activity {
TextView tv;
ArrayList<Object> objarray = new ArrayList<Object>(2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
makeObjects();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void makeObjects(){
//For loop creates two objects and adds them to the list
for(int i = 0; i < 3; i++) {
int number=1;
String word="One";
number++;
objectdata o = new objectdata(number, word);
objarray.add(o);
}
//THIS IS WRONG!
//Access the second object in the list, so as to access the value in number
objectdata o = objarray.get(1);
tv.setText(o.number.toString());
}
}
在底部我尝试访问索引1中的对象,所以创建的第二个对象,我想通过使用该对象从类中获取数值并将其存储在文本视图中,以便我可以看到它的工作原理。基本上我试图使用对象来存储数据,然后将这些对象存储在数组列表中。我完全停留在这一点上。
究竟发生了什么问题? – Egor 2013-03-12 16:01:05
那么我写的代码,我评论这是错误的,代码是错误的,并给我一个错误,我无法运行它,因为我不知道这样做的正确语法。 – deucalion0 2013-03-12 16:11:00