java怎么创建一个对象来存放数组的值。

2024-12-26 17:29:55
推荐回答(4个)
回答1:

public class Test{
public static void main(String[] args) {
User[] users = new User[8];
Test t = new Test();
users[0] = t.new User("1", "type", "username");
users[1] = t.new User("2", "type", "username");
users[2] = t.new User("3", "type", "username");
users[3] = t.new User("4", "type", "username");
users[4] = t.new User("5", "type", "username");
users[5] = t.new User("6", "type", "username");
users[6] = t.new User("7", "type", "username");
users[7] = t.new User("8", "type", "username");
}

class User{

public User(String id, String type, String username){
this.id = id;
this.type = type;
this.username = username;
}

public String type;
public String id;

public String username;

}
}

回答2:

如果是定值非常好弄;
Object [][]obj = new Object [8][3];//如果确认是String ,可以直接定义成String 类型
for(int i = 0; i<8;i++){
obj[i][0] = Type[i];
obj[i][1] = id[i];
obj[i][2] = username[i];
}
//obj里面应该存储的就是你想要的东西了。

回答3:

把数字中的每项作为对象中的一个字段

回答4:

//新建一个类User用来存放这,三个数据
//结果放到一个User数组中,你看这可以吗?
//还是说要放到一个list中?

public class ObjectTest {

public static void main(String[] args) {
String[] id = new String[8];
String[] type = new String[8];
String[] username = new String[8];

User[] users = getUsers(type, id, username);
}

private static User[] getUsers(String[] type, String[] id, String[] username) {
User[] users = new User[type.length];
for (int i = 0; i < type.length; i++) {
users[i] = new User(id[i], type[i], username[i]);
}
return users;
}
}

class User {

public User(String id, String tpye, String username) {
this.tpye = tpye;
this.id = id;
this.username = username;
}

private String tpye;
private String id;
private String username;

public String getTpye() {
return this.tpye;
}

public String getId() {
return this.id;
}

public String getUsername() {
return this.username;
}

public void setTpye(String tpye) {
this.tpye = tpye;
}

public void setId(String id) {
this.id = id;
}

public void setUsername(String username) {
this.username = username;
}

}