2017-02-08 5 views

Antwort

0

jedes Attribut der Person Klasse Angenommen ist ein Element in dem String-Array, wird im Folgenden die Arbeit machen:

Person Klasse:

public class Person { 
private String title; 
private String firstName; 
private String lastName; 

public Person(String title, String firstName, String lastName) { 
    super(); 
    this.title = title; 
    this.firstName = firstName; 
    this.lastName = lastName; 
} 

public String getTitle() { 
    return title; 
} 

public void setTitle(String title) { 
    this.title = title; 
} 

public String getFirstName() { 
    return firstName; 
} 

public void setFirstName(String firstName) { 
    this.firstName = firstName; 
} 

public String getLastName() { 
    return lastName; 
} 

public void setLastName(String lastName) { 
    this.lastName = lastName; 
} 

} 

PersonConverter Klasse:

import java.util.ArrayList; 
import java.util.List; 

public class PersonConverter { 

public List<String[]> convertPersonList(List<Person> list) { 
    List<String[]> result = new ArrayList<>(); 

    for (Person p : list) { 
     result.add(convertPerson(p)); 
    } 

    return result; 
} 

private String[] convertPerson(Person p) { 
    String[] persontAttributes = new String[3]; 
    persontAttributes[0] = p.getTitle(); 
    persontAttributes[1] = p.getFirstName(); 
    persontAttributes[2] = p.getLastName(); 
    return persontAttributes; 
} 
} 

Der Test:

import java.util.ArrayList; 
import java.util.List; 

public class Main { 

public static void main(String[] args) { 
    //create a person list 
    List<Person> personList = new ArrayList<>(); 

    Person john = new Person("Mr.", "John", "Lenonn"); 
    Person paul = new Person("Sir", "Paul", "McCartney"); 

    personList.add(john); 
    personList.add(paul); 

    //create an instance of the person converter 
    PersonConverter pc = new PersonConverter(); 

    //perform the conversion 
    List<String[]> convertedList = pc.convertPersonList(personList); 

    //print the result to the console 
    for (String[] stringArray : convertedList) { 
     for (String s : stringArray) { 
      System.out.println(s); 
     } 
     System.out.println(); 
    } 
} 

} 

Dies gibt:

Mr. 
John 
Lenonn 

Sir 
Paul 
McCartney 
0

Ich bin mir nicht sicher, ob ich klar verstehe, was Sie verlangen, aber Sie können immer eine einfache Schleife über Ihre Personen machen.

ArrayList<Person> people = new ArrayList<Person>(); 
List<String[]> everyonesAtt = new ArrayList<String[]>(); 
for (Person person : people) { 
    everyonesAtt.add(person.getAttributes()); 
} 

Und ein Beispiel für Klasse Person:

public class Person { 

private String name; 

private String surname; 

public String[] getAttributes(){ 
    String[] atts = {name, surname}; 
    return atts; 
} 
} 
Verwandte Themen