How to insert values in two dimensional array programmatically?

后端 未结 6 1340
栀梦
栀梦 2020-12-10 15:48

I want to do this dynamically in java. I know how to insert values in single dimensional array. I am bit confused in two dimensional array.

static final Str         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 16:15

    In case you don't know in advance how many elements you will have to handle it might be a better solution to use collections instead (https://en.wikipedia.org/wiki/Java_collections_framework). It would be possible also to create a new bigger 2-dimensional array, copy the old data over and insert the new items there, but the collection framework handles this for you automatically.

    In this case you could use a Map of Strings to Lists of Strings:

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    public class MyClass {
        public static void main(String args[]) {
            Map> shades = new HashMap<>();
    
            ArrayList shadesOfGrey = new ArrayList<>();
            shadesOfGrey.add("lightgrey");
            shadesOfGrey.add("dimgray");
            shadesOfGrey.add("sgi gray 92");
    
            ArrayList shadesOfBlue = new ArrayList<>();
            shadesOfBlue.add("dodgerblue 2");
            shadesOfBlue.add("steelblue 2");
            shadesOfBlue.add("powderblue");
    
            ArrayList shadesOfYellow = new ArrayList<>();
            shadesOfYellow.add("yellow 1");
            shadesOfYellow.add("gold 1");
            shadesOfYellow.add("darkgoldenrod 1");
    
            ArrayList shadesOfRed = new ArrayList<>();
            shadesOfRed.add("indianred 1");
            shadesOfRed.add("firebrick 1");
            shadesOfRed.add("maroon 1");
    
            shades.put("greys", shadesOfGrey);
            shades.put("blues", shadesOfBlue);
            shades.put("yellows", shadesOfYellow);
            shades.put("reds", shadesOfRed);
    
            System.out.println(shades.get("greys").get(0)); // prints "lightgrey"
        }
    }
    

提交回复
热议问题