Create an array of array in java
I need to create an array of array with Strings in java...
For example, I read a file that contain for each column a sport and a player name..like:
The goal at the end it's for populate a list grouped in section (sports)
hockey,Wayne Gretsky
hockey,Mario Lemieux
baseball,Barry Bonds
baseball,A Rod
I need to create the [][] with this function :
public static String[][] getSportItems(int sectionCount){
String currentSection="";
int cnt=0;
try{
开发者_Python百科 File file = new File(Environment.getExternalStorageDirectory()
+ "/sports.csv");
BufferedReader br = new BufferedReader(new FileReader(file));
String strLine = "";
while ((strLine = br.readLine()) != null) {
String[] data = strLine.split(";");
if(cnt>0){
}
cnt++;
}
}catch (IOException e) {
e.printStackTrace();
}
}
How I can manage that to create an array for each sport that contain the players associated with the sports.
I'm new in Java... Thanks
Bonjour Maxime,
you should better store you data in a hasmap. This allows to associate some value to another. For instance, you could define a map that associates a sport to a list of player like this :
Map<String, List<Player>> mapSportToPlayer = new Hashmap<String, List<Player>>();
or if you don't have a Player class (but better have one) :
Map<String, List<String>> mapSportToPlayer = new Hashmap<String, List<String>>();
and to put a player, do like this
public void addPlayerToSport( String sport, Player player )
{
List<Player> listPlayer = mapSportToPlayer.get( sport );
//first time we associate a player to this sport
if( listPlayer == null )
{
listPlayer = new ArrayList<Player>();
}//if
listPlayer.add( player );
}//met
and to get all people associated with a sport :
List listPlayer = mapSportToPlayer.get( sport );
and print them out on console
for( Player p : listPlayer )
System.out.println( p );
and then override toString in class player to provide a clear text output of your objects.
Regards, Stéphane
A Map is a better way of storing this. But if you want an array you can create a two dimensional array or an array of arrays e.g.
String[][] sportToPlayers = {{"hockey","Wayne Gretsky"},
{"hockey","Mario Lemieux"},{"baseball", "Barry Bonds"}};
So each Array has two values. At position 0 is the sport and position 1 is the player name
Or you could just assert that in position 0 it's hockey and position 1 it's baseball i.e.
String[][] playersOfSports = {{"Mario Lemieux","Wayne Gretsky"},
},{"Barry Bonds", "A Rod"}}
or if the use of arrays is a constraint in the problem/HW you can create an array of Objects and store in it another array since the Object class is ontop of all classes and then cast the object as an array whenever you want to youse it
String[][] playerSport = new String[7][2];
If the number of rows is not fixed, use ArrayList
.
List<String[]> listPlayerSport = new ArrayList<String[]>();
精彩评论