Synoon
Synoon

Reputation: 2351

Reference on an 2D-Array-Element

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

    }
}

Is it possible to create such a reference in java? So I can save an array-element(

{"Marc","Empten"}

) from the array?

So I can use only the oneperson variable to give out the "Marc Empten"? I have no Idea how to realise this. Is it even possible?

Upvotes: 1

Views: 56

Answers (3)

stevecross
stevecross

Reputation: 5684

You would have to write something like this:

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]);
    }
}

This only works if you know for sure that the inner arrays always contain 2 elements. If not you would have to use a loop to print the name for example (note that the last name has 3 parts):

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();
}

Upvotes: 1

Syam S
Syam S

Reputation: 8509

If you want to just print an array use Arrays.toString() method. But the better approach her would be to make a class Name which hold both parts. Then use an array list to store the names. Like

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}

    }
}

Upvotes: 2

Sanjeev
Sanjeev

Reputation: 9946

Do it like this:

System.out.println(Arrays.toString((Object[])oneperson));

Upvotes: 1

Related Questions