如何组织不同类型的数组?

时间:2012-06-20 10:33:15

标签: java arrays multidimensional-array

您好,

我是Java新手并试图弄清楚如何将这些数据推入数组(6行,3列)?

x1 John 6
x2 Smith 9
x3 Alex 7
y1 Peter 8
y2 Frank 9
y3 Andy 4

之后,我将从最后一栏获取数字进行数学计算。

这是我的代码......

public class Testing {
    public static void main(String[] args) {

        Employee eh = new Employee_hour();

        Employee_hour [] eh_list = new Employee_hour[6];
        eh_list[0] = new Employee_hour("x1", "John", 6);
        eh_list[1] = new Employee_hour("x2", "Smith", 9);
        eh_list[2] = new Employee_hour("x3", "Alex", 7);
        eh_list[3] = new Employee_hour("y1", "Peter", 8);
        eh_list[4] = new Employee_hour("y2", "Frank", 9);
        eh_list[5] = new Employee_hour("y3", "Andy", 4);
        print(eh_list);
    }

    private static void print(Employee_hour[] mass){
        for (int i = 0; i < mass.length; i++) {
            System.out.print(mass[i] + " ");
        }
        System.out.println();
    }
}

但我把它作为输出......

  

testing.Employee_hour@1a752144 testing.Employee_hour@7fdb04ed   testing.Employee_hour@420a52f testing.Employee_hour@7b3cb2c6   testing.Employee_hour@4dfd245f testing.Employee_hour@265f00f9

如何从最后一栏获得数字?

5 个答案:

答案 0 :(得分:9)

为什么不为您的记录创建特定的Java bean?

class Person {
  String id;
  String name;
  int anotherNumber;
  // constructor, getters, setters
}

然后像这样使用它:

Person [] people = new Person[10];
people[0] = new Person("x1", "John", 6);
...

或者更好地使用java.util.List代替数组。

字段访问

要访问单独的字段,您需要将字段公开(非常糟糕)并简单地将其称为object_instance.field_name,或者提供所谓的getter:

class Person {
  String id;
  String name;
  int anotherNumber;
  // constructor, getters, setters

  public int getAnotherNumber() {
     return anotherNumber;
  }
}

然后在打印时调用它:

for (int i = 0; i < mass.length; i++) {
    System.out.print(mass[i].getAnotherNumber() + " ");
}

为什么你尝试的不起作用:

在您的情况下,

System.out.println(mass[0])将打印整个对象表示,默认情况下会打印它在您的情况下执行的操作。要做得更好,您需要覆盖Object的{​​{1}}方法:

String toString()

答案 1 :(得分:3)

Java是强类型的,所以你不能只创建一个接受任何类型的数组 但是,您可以创建类型为Object的多维数组,并使用java.lang.Integer作为整数值。
另一种方法是创建一个表示表中行的类,并创建该类的数组。

答案 2 :(得分:2)

如果你想把它存储为数组用户2维数组。这是一个样本。

String[][] a2 = new String[10][5];
   for (int i=0; i<a2.length; i++) {
   for (int j=0; j<a2[i].length; j++) {
   a2[i][j] = i;
   System.out.print(" " + a2[i][j]);
   }
   System.out.println("");
   }
  }

更好的方法是创造一个对象

class User {
  String id;
  String userName;
  int userSomeValue;

 //
}

然后将其推送到列表

User ob1=new User();
// set the values.
List<User> userList=new ArrayList<User>();
userList.add(ob1);

使用此列表通过使用

重新检索内容进行处理
userList.get(index);

答案 3 :(得分:1)

Array是一个类型安全的集合,您可以使用通用对象数组。其他方式使用collection Api

答案 4 :(得分:0)

有一些方法可以将数据存储在数组中,但只能在同一个数组中存储相同类型的值。例如,String,int或float。在您的情况下,您必须使用String,但即使它包含数字,您也无法使用字符串类型变量进行任何计算。我会建议maksimov描述的方式。

相关问题