Java 创建具有多种对象类型的 ArrayList?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19602601/
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
Create an ArrayList with multiple object types?
提问by Dakshila Kamalsooriya
How do I create an ArrayList
with integer and string input types? If I create one as:
如何创建ArrayList
整数和字符串输入类型?如果我创建一个:
List<Integer> sections = new ArrayList <Integer>();
that will be an Integer
type ArrayList
.
If I create one as:
那将是一种Integer
类型ArrayList
。如果我创建一个:
List<String> sections = new ArrayList <String>();
that will be of String
type.
How can I create an ArrayList
which can take both integer and string input types?
Thank you.
那将是String
类型。如何创建一个ArrayList
既可以接受整数又可以接受字符串输入类型的对象?谢谢你。
采纳答案by AKHY
User Defined Class Array List Example
用户定义类数组列表示例
import java.util.*;
public class UserDefinedClassInArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Program Output:
程序输出:
1 AAA 13
1 AAA 13
2 BBB 14
2 BBB 14
3 CCC 15
3 CCC 15
回答by Hovercraft Full Of Eels
You could create a List<Object>
, but you really don't want to do this. Mixed lists that abstract to Object are not very useful and are a potential source of bugs. In fact the fact that your code requires such a construct gives your code a bad code smell and suggests that its design may be off. Consider redesigning your program so you aren't forced to collect oranges with orangutans.
您可以创建一个List<Object>
,但您真的不想这样做。抽象为 Object 的混合列表不是很有用,并且是错误的潜在来源。事实上,您的代码需要这样的结构这一事实给您的代码带来了糟糕的代码味道,并表明其设计可能是错误的。考虑重新设计您的程序,这样您就不会被迫与猩猩一起收集橙子。
Instead -- do what G V recommends and I was about to recommend, create a custom class that holds both int and String and create an ArrayList of it. 1+ to his answer!
相反——按照 GV 的建议和我将要推荐的做法,创建一个包含 int 和 String 的自定义类并创建它的 ArrayList。1+他的回答!
回答by Gaurav Varma
You can make it like :
你可以让它像:
List<Object> sections = new ArrayList <Object>();
(Recommended) Another possible solution would be to make a custom model class with two parameters one Integer and other String. Then using an ArrayList
of that object.
(推荐)另一种可能的解决方案是使用两个参数一个整数和另一个字符串创建一个自定义模型类。然后使用ArrayList
该对象的 。
回答by Prabhakaran Ramaswamy
You don't know the type is Integer or String then you no need Generic. Go With old style.
你不知道类型是整数还是字符串,那么你不需要泛型。走旧风格。
List list= new ArrayList ();
list.add(1);
list.add("myname");
for(Object o = list){
}
回答by Sanket Parikh
You can use Object for storing any type of value for e.g. int, float, String, class objects, or any other java objects, since it is the root of all the class. For e.g.
您可以使用 Object 来存储任何类型的值,例如 int、float、String、类对象或任何其他 java 对象,因为它是所有类的根。例如
Declaring a class
class Person { public int personId; public String personName; public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; }}
main function code, which creates the new person object, int, float, and string type, and then is added to the List, and iterated using for loop. Each object is identified, and then the value is printed.
Person p = new Person(); p.setPersonId(1); p.setPersonName("Tom"); List<Object> lstObject = new ArrayList<Object>(); lstObject.add(1232); lstObject.add("String"); lstObject.add(122.212f); lstObject.add(p); for (Object obj : lstObject) { if (obj.getClass() == String.class) { System.out.println("I found a string :- " + obj); } if (obj.getClass() == Integer.class) { System.out.println("I found an int :- " + obj); } if (obj.getClass() == Float.class) { System.out.println("I found a float :- " + obj); } if (obj.getClass() == Person.class) { Person person = (Person) obj; System.out.println("I found a person object"); System.out.println("Person Id :- " + person.getPersonId()); System.out.println("Person Name :- " + person.getPersonName()); } }
声明一个类
class Person { public int personId; public String personName; public int getPersonId() { return personId; } public void setPersonId(int personId) { this.personId = personId; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; }}
main函数代码,创建新的person对象,int、float、string类型,然后添加到List中,使用for循环进行迭代。识别每个对象,然后打印值。
Person p = new Person(); p.setPersonId(1); p.setPersonName("Tom"); List<Object> lstObject = new ArrayList<Object>(); lstObject.add(1232); lstObject.add("String"); lstObject.add(122.212f); lstObject.add(p); for (Object obj : lstObject) { if (obj.getClass() == String.class) { System.out.println("I found a string :- " + obj); } if (obj.getClass() == Integer.class) { System.out.println("I found an int :- " + obj); } if (obj.getClass() == Float.class) { System.out.println("I found a float :- " + obj); } if (obj.getClass() == Person.class) { Person person = (Person) obj; System.out.println("I found a person object"); System.out.println("Person Id :- " + person.getPersonId()); System.out.println("Person Name :- " + person.getPersonName()); } }
You can find more information on the object class on this link Object in java
您可以在此链接Object in java上找到有关对象类的更多信息
回答by shikjohari
You can always create an ArrayList
of Object
s. But it will not be very useful to you. Suppose you have created the Arraylist
like this:
你总是可以创建一个ArrayList
of Object
s。但它对你不会很有用。假设你已经创建了Arraylist
这样的:
List<Object> myList = new ArrayList<Object>();
List<Object> myList = new ArrayList<Object>();
and add objects to this list like this:
并将对象添加到此列表中,如下所示:
myList.add(new Integer("5"));
myList.add(new Integer("5"));
myList.add("object");
myList.add("object");
myList.add(new Object());
myList.add(new Object());
You won't face any problem while adding and retrieving the object but it won't be very useful.
You have to remember at what location each type of object is it in order to use it. In this case after retrieving, all you can do is calling the methods of Object
on them.
添加和检索对象时不会遇到任何问题,但它不会很有用。您必须记住每种类型的对象在什么位置才能使用它。在这种情况下,检索后,您所能做的就是调用Object
它们的方法。
回答by dantiston
I am also newish to Java and just figured this out. You should create your own class which stores the string and integer, and then make a list of these objects. For instance (I am sure this code is imperfect, but better than arrayList):
我也是 Java 新手,刚刚想通了这一点。您应该创建自己的类来存储字符串和整数,然后列出这些对象。例如(我确信这段代码不完美,但比 arrayList 好):
class Stuff {
private String label;
private Integer value;
// Constructor or setter
public void Stuff(String label, Integer value) {
if (label == null || value == null) {
return;
}
this.label = label;
this.value = value;
}
// getters
public String getLabel() {
return this.label;
}
public Integer getValue() {
return this.value;
}
}
Then in your code:
然后在你的代码中:
private ArrayList<Stuff> items = new ArrayList<Stuff>();
items.add(new Stuff(label, value));
for (Stuff item: items) {
doSomething(item.getLabel()); // returns String
doSomething(item.getValue()); // returns Integer
}
回答by user3777313
You can just add objects of diffefent "Types" to an instance of ArrayList. No need create an ArrayList. Have a look at the below example,
You will get below output:
Beginning....
Contents of array: [String, 1]
Size of the list: 2
This is not an Integer String
This is an Integer 1
您可以将不同“类型”的对象添加到 ArrayList 的实例中。无需创建 ArrayList。看看下面的例子,你会得到以下输出:
Beginning....
数组内容:[String, 1]
列表大小:2
This is not an Integer String
This is an Integer 1
package com.viswa.examples.programs;
import java.util.ArrayList;
import java.util.Arrays;
public class VarArrayListDemo {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
System.out.println(" Beginning....");
ArrayList varTypeArray = new ArrayList();
varTypeArray.add("String");
varTypeArray.add(1); //Stored as Integer
System.out.println(" Contents of array: " + varTypeArray + "\n Size of the list: " + varTypeArray.size());
Arrays.stream(varTypeArray.toArray()).forEach(VarArrayListDemo::checkType);
}
private static <T> void checkType(T t) {
if (Integer.class.isInstance(t)) {
System.out.println(" This is an Integer " + t);
} else {
System.out.println(" This is not an Integer" + t);
}
}
}
回答by Ali
List<Object> list = new ArrayList<>();
list.add(1);
list.add("1");
As the return type of ArrayList is object, you can add any type of data to ArrayList but it is not a good practice to use ArrayList because there is unnecessary boxing and unboxing.
由于 ArrayList 的返回类型是对象,因此您可以向 ArrayList 添加任何类型的数据,但使用 ArrayList 不是一个好习惯,因为有不必要的装箱和拆箱。
回答by Darshana Ekanayake
(1)
(1)
ArrayList<Object> list = new ArrayList <>();`
list.add("ddd");
list.add(2);
list.add(11122.33);
System.out.println(list);
(2)
(2)
ArrayList arraylist = new ArrayList();
arraylist.add(5);
arraylist.add("saman");
arraylist.add(4.3);
System.out.println(arraylist);