简体   繁体   中英

Mapping Array List in java

I trying to run this code in java:

List<Map<String , String>> studentList = new ArrayList<>();
Map<String , String> studentRecord = new HashMap();

//Record for first Student
studentRecord.put("Name","aaa");
studentRecord.put("Age","22");
studentRecord.put("Sex","m");
studentList.add(studentRecord);

//Record for second Student
studentRecord.put("Name","bbb");
studentRecord.put("Age","44");
studentRecord.put("Sex","f");
studentList.add(studentRecord);

and the output is:

[{Sex=f,Age=44,Name=bbb},{Sex=f,Age=44,Name=bbb}]

instead of

 [{Sex=m,Age=22,Name=aaa},{Sex=f,Age=44,Name=bbb}]
  • a. What am I doing wrong?
  • b.let's say that the output is correct. How can I print only the "Name" value of StudentList[0] which mean "aaa" ?

Thanks

You have one map instance:

Map<String , String> studentRecord = new HashMap();

which you add to the list twice.

When you call studentRecord.put for the second student, you are calling this on the one and only map instance , thus overriding the keys from the first student.

The best solution is: don't use a map to represent a data object . Use a class. It's what they were designed for.

enum Sex
{
    MALE, FEMALE
}

class Student
{
    private final String name;
    private final int age;
    private final Sex sex;

    Student(String name, int age, Sex sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    // getters...
}

List<Student> students = new ArrayList<>();
students.add(new Student("aaa", 222, Sex.MALE));
students.add(new Student("bbb", 44, Sex.FEMALE));

If you just want the quick and dirty solution, you can use this:

//Record for second Student
studentRecord = new HashMap<>(); // I added this line

studentRecord.put("Name","bbb");
studentRecord.put("Age","44");
studentRecord.put("Sex","f");
studentList.add(studentRecord);

which creates a second HashMap for the second student, thus ensuring the keys from the first map are not overridden.

When you invoke ".add()" on your ArrayList - you are putting the HashMap refetence into it:

    List<Map<String , String>> studentList = new ArrayList<>();
    Map<String , String> studentRecord = new HashMap();

    studentRecord.put("Name","aaa");
    studentRecord.put("Age","222");
    studentRecord.put("Sex","m");
    studentList.add(studentRecord);
    studentList.forEach(map -> System.out.println(map.hashCode()));
    System.out.println("--------");


    studentRecord.put("Name","bbb");
    studentRecord.put("Age","44");
    studentRecord.put("Sex","f");
    studentList.add(studentRecord);
    studentList.forEach(map -> System.out.println(map.hashCode()));
}

So then you change the state of HashMap and putting it again. The output will be:

2661442
--------
2612488
2612488

So, you are just working with 1 object, instead of working with 2 different objects.

It looks like you need a class "Student" to work with it, it would be more "Java-style":

public class Main {

        public static void main(String[] args) {

            List<Student> students = new ArrayList<>();
            students.add(new Student("aaa", 222, "m"));
            students.add(new Student("bbb", 44, "f"));

            System.out.println(students);
    }
}

class Student {
    String name;
    Integer age;
    String sex;

    public Student(String name, Integer age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
            "name='" + name + '\'' +
            ", age=" + age +
            ", sex='" + sex + '\'' +
            '}';
    }
}

You are creating only one instance of Map. Hence, loosing the record. Please create two instance of map as below:

List<Map<String, String>> studentList = new ArrayList<>();

//First instance
Map<String, String> studentRecord1 = new HashMap();

//Record for first Student
studentRecord1.put("Name", "aaa");
studentRecord1.put("Age", "22");
studentRecord1.put("Sex", "m");
studentList.add(studentRecord1);

//Second instance
Map<String, String> studentRecord2 = new HashMap();

//Record for second Student
studentRecord2.put("Name", "bbb");
studentRecord2.put("Age", "44");
studentRecord2.put("Sex", "f");
studentList.add(studentRecord2);

this code return an array with all you need:

package Test;
import java.awt.event.KeyEvent;                                                               
import java.lang.reflect.Field;                                                               
import java.lang.reflect.Modifier;                                                            
import java.util.*;                                                                           
                                                                                              
public class Test {                 
    public static void main(String[] a) {   
        ArrayList<Integer> ints = new ArrayList<Integer>();
        ArrayList<String> strs = new ArrayList<String>();
        
        for(int i = 0; i < 1000000; ++i) {                                                    
            String text = java.awt.event.KeyEvent.getKeyText(i);                              
            if(!text.contains("Unknown keyCode: ")) {                                         
                strs.add("\""+text+"\"");
                ints.add(i);
            }                                                                                 
        }                                                                                     
        
        System.out.println(ints);
        System.out.println(strs);
    }                                                                                         
}

output:

[3, 8, 9, 10, 12, 16, 17, 18, 19, 20, 21, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 59, 61, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 150, 151, 152, 153, 154, 155, 156, 157, 160, 161, 162, 192, 222, 224, 225, 226, 227, 240, 241, 242, 243, 244, 245, 256, 257, 258, 259, 260, 261, 262, 263, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 61440, 61441, 61442, 61443, 61444, 61445, 61446, 61447, 61448, 61449, 61450, 61451, 65312, 65368, 65406, 65480, 65481, 65482, 65483, 65485, 65487, 65488, 65489]
["Cancel", "Backspace", "Tab", "Enter", "Clear", "Shift", "Ctrl", "Alt", "Pause", "Caps Lock", "Kana", "Final", "Kanji", "Escape", "Convert", "No Convert", "Accept", "Mode Change", "Space", "Page Up", "Page Down", "End", "Home", "Left", "Up", "Right", "Down", "Comma", "Minus", "Period", "Slash", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "Semicolon", "Equals", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "Open Bracket", "Back Slash", "Close Bracket", "NumPad-0", "NumPad-1", "NumPad-2", "NumPad-3", "NumPad-4", "NumPad-5", "NumPad-6", "NumPad-7", "NumPad-8", "NumPad-9", "NumPad *", "NumPad +", "NumPad ,", "NumPad -", "NumPad .", "NumPad /", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "Delete", "Dead Grave", "Dead Acute", "Dead Circumflex", "Dead Tilde", "Dead Macron", "Dead Breve", "Dead Above Dot", "Dead Diaeresis", "Dead Above Ring", "Dead Double Acute", "Dead Caron", "Dead Cedilla", "Dead Ogonek", "Dead Iota", "Dead Voiced Sound", "Dead Semivoiced Sound", "Num Lock", "Scroll Lock", "Ampersand", "Asterisk", "Double Quote", "Less", "Print Screen", "Insert", "Help", "Meta", "Greater", "Left Brace", "Right Brace", "Back Quote", "Quote", "Up", "Down", "Left", "Right", "Alphanumeric", "Katakana", "Hiragana", "Full-Width", "Half-Width", "Roman Characters", "All Candidates", "Previous Candidate", "Code Input", "Japanese Katakana", "Japanese Hiragana", "Japanese Roman", "Kana Lock", "Input Method On/Off", "At", "Colon", "Circumflex", "Dollar", "Euro", "Exclamation Mark", "Inverted Exclamation Mark", "Left Parenthesis", "Number Sign", "Plus", "Right Parenthesis", "Underscore", "Windows", "Context Menu", "F13", "F14", "F15", "F16", "F17", "F18", "F19", "F20", "F21", "F22", "F23", "F24", "Compose", "Begin", "Alt Graph", "Stop", "Again", "Props", "Undo", "Copy", "Paste", "Find", "Cut"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM