简体   繁体   English

如何访问对象列表中的元素

[英]How can I access elements within a list of Objects

I'm defining an ArrayList as such我正在定义一个 ArrayList

ArrayList <Object> p = new ArrayList<Object>();

now to the ArrayList I'm adding like so现在到ArrayList我像这样添加

String source = "hi";
int x,y,year = 0;
p.add(new Object(source,x,y,year));
p.add(new Object(source+"hello",x+1,y+1,year+1));

Now in the main method, I want to access a specific element within the the list of Objects.现在在 main 方法中,我想访问对象列表中的特定元素。 How would I do that?我该怎么做?

When I print it out in the main method, it outputs当我在 main 方法中打印出来时,它输出

[source,x,y,year, source1,x1,y1,year1] 

However, I want just the source from the first element.但是,我只想要第一个元素的来源。 So output just "hi" as type String not as a object.所以只输出“hi”作为字符串类型而不是对象。

One way to achieve your desired result is by putting the arguments in a list by using Arrays.asList() .实现所需结果的一种方法是使用Arrays.asList()将参数放入列表中。 Something like this.像这样的东西。

ArrayList<List> listOfList = new ArrayList<List>();
        
String greetings = "hi";
int x = 0, y = 0, year = 0;
        
listOfList.add(Arrays.asList(greetings, x, y, year));
listOfList.add(Arrays.asList(greetings + " hello", ++x, ++y, ++year));
        
//Get and print list of the first list.
List listA = listOfList.get(0);
for(Object obj : listA) {
    System.out.print(obj + " ");
}
System.out.println();
//Prints: "hi 0 0 0 "
        
//Print the second list.
System.out.println(listOfList.get(1));
//Prints: "[hi hello, 1, 1, 1]"

p.get(0) would get you the first object in the list. p.get(0)会让你得到列表中的第一个对象。

Java is object oriented. Java是面向对象的。 Objects define what you can do with them.对象定义了你可以用它们做什么。 They don't "have" a property unless whomever wrote the class decides that it should have it.他们没有“拥有”属性,除非编写该类的人决定它应该拥有它。

Thus, your question is unanswerable without the source code of whatever Object is in your question.因此,如果没有您问题中任何Object的源代码,您的问题是无法回答的。 Presumably it has a .getSource() method which returns it.大概它有一个返回它的.getSource()方法。 If it does: p.get(0).getSource() would do the job.如果是这样: p.get(0).getSource()将完成这项工作。 If it doesn't, find the method that does that job, and if it doesn't exist, write it, and if you didn't write that class, then you can't do it.如果没有,找到做那个工作的方法,如果它不存在,就写它,如果你没有写那个类,那么你就做不到。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM