public class ReferenceTest {
public static void main(String[] args) {
String[][] names = {{"George","Hampton"},{"Marc", "Empten"},{"Levin", "Lian"}};
Object oneperson; //Reference to one object of the 2D Array
oneperson = names[1];
//Output should be Marc Empten
System.out.println(oneperson.toString()); //[Ljava.lang.String;@11890d
}
}
是否可以在java中创建这样的引用?所以我可以保存一个数组元素(
{"马克"" Empten"}
)来自阵列?
所以我只能使用oneperson变量来表示" Marc Empten"? 我不知道如何实现这一点。它甚至可能吗?
答案 0 :(得分:2)
如果您只想使用Arrays.toString()
方法打印数组。但是,更好的方法是制作一个包含两个部分的名称。然后使用数组列表来存储名称。像
class Name{
private String firstName;
private String lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "{" + firstName + ", " + lastName
+ "}";
}
// Getters & Setters
}
public class Sample {
public static void main(String[] args) throws JsonProcessingException {
List<Name> names = new ArrayList<Name>(Arrays.asList(new Name[] { new Name("George","Hampton"), new Name("Marc", "Empten"), new Name("Levin", "Lian")}));
System.out.println(names.get(1)); // Prints {Marc, Empten}
}
}
答案 1 :(得分:1)
你必须写下这样的东西:
public class ReferenceTest {
public static void main(String[] args) {
// An array of arrays of Strings
String[][] names = {{"George","Hampton"},{"Marc", "Empten"},{"Levin", "Lian"}};
// An array of Strings
String[] marc = names[1];
//Output is Marc Empten
System.out.println(marc[0] + " " + marc[1]);
}
}
仅当您确定内部数组始终包含2个元素时,此方法才有效。如果没有,你将不得不使用循环来打印名称(例如,姓氏有3个部分):
final String[][] names =
{ { "George", "Hampton" }, { "Marc", "Empten" }, { "Levin", "Lian" }, { "John", "James", "Rambo" } };
for (final String[] name : names) {
for (final String partial : name) {
System.out.print(partial);
System.out.print(" ");
}
System.out.println();
}
答案 2 :(得分:1)
这样做:
System.out.println(Arrays.toString((Object[])oneperson));