2017-04-07 85 views
0

我有一个由字符串,双精度和整数组成的变量列表,我想将它们存储在一个列表中,遍历列表并根据数据类型执行不同的操作。如何创建不同数据类型的列表,根据类型迭代并执行不同的操作?

最初我以为我可以创建一个ArrayList来实现这一点,但其中一些是原始类型而不是对象,所以这不起作用。

我不知道列表中每个项目有多少,所以我不认为我可以创建一个对象来保存所有不同的类型。

达到此目的的最佳方法是什么?

+0

*为什么*你想这样做?也许有更好的方法来实现这一点。 –

+2

您是否意识到每种基元类型都存在包装类?请参阅[维基百科文章](https://en.wikipedia.org/wiki/Primitive_wrapper_class)。此外,[autoboxin/unboxing](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html)更加简化了这一点。 –

+0

你会发现你的ArrayList已经包含了你添加到它的原始类型的包装器。 –

回答

1
  1. 由于我们可以存储任何类型,类也是实现此目的的替代方法。在 以下解决方案我创建了具有不同类型 变量的Employee类。

    public class Employee { 
    
        static List<Employee> employeeList = new ArrayList<Employee>(); 
        private int id; 
        private String firstName; 
        private int age; 
        private double salary; 
        private String department; 
    
        public Employee(int id, String firstName, int age, double salary, 
        String department) { 
        this.id = id; 
        this.firstName = firstName; 
        this.age = age; 
        this.salary = salary; 
        this.department = department; 
        } 
    
        public static void main(String[] argv) { 
        Employee employee1 = new Employee(1, "Pavan", 45, 20000.00, 
        "Uppal"); 
        Employee employee2 = new Employee(2, "Mahesh", 35, 10000.00, 
        "Uppal");  
    
        employeeList.add(employee1); 
        employeeList.add(employee2); 
    
        } 
    
    } 
    

    2.其他替代方法是创建对象类型的ArrayList

    List<Object> list=new Arraylist<Object>(); 
    list.add(100); 
    list.add("hi") 
    list.add(12.0) 
    
0

可以始终使用对象表示从原始类型像浮动而不是浮子,整型,而不是整数,等。通过这种方式,您可以使用null概念而不是默认值来识别数据无效的情况,这与原始类型会发生的情况相同。 如果你想要一个特殊的行为,你可以实现一些模式,如访客模式(https://www.tutorialspoint.com/design_pattern/visitor_pattern.htm)。

相关问题