java - 插入到 HashMap 中会导致排序困惑

标签 java android hashmap

基于该类

public class Record {
    public static final String TABLE_NAME = "records";

    public static final String COLUMN_ID = "id";
    public static final String COLUMN_LONGITUDE = "longitude";
    public static final String COLUMN_LATITUDE = "latitude";
    public static final String COLUMN_SPEED = "speed";
    public static final String COLUMN_TIMESTAMP = "timestamp";

    private int id;
    private String longitude;
    private String latitude;
    private String speed;
    private String timestamp;

    public static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_LONGITUDE + " TEXT,"
                + COLUMN_LATITUDE + " TEXT,"
                + COLUMN_SPEED + " TEXT,"
                + COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT (DATETIME('now','localtime'))"
            + ")";

    public Record(){
    }

    public Record(int id, String longitude, String latitude, String speed, String timestamp){
        this.id = id;
        this.longitude = longitude;
        this.latitude = latitude;
        this.speed = speed;
        this.timestamp = timestamp;
    }

    public int getId(){
        return id;
    }

    public String getLongitude(){
        return longitude;
    }

    public String getLatitude(){
        return latitude;
    }

    public String getSpeed(){
        return speed;
    }

    public String getTimestamp(){
        return timestamp;
    }

    public void setId(int id){
        this.id = id;
    }

    public void setLongitude(String longitude){
        this.longitude = longitude;
    }

    public void setLatitude(String latitude){
        this.latitude = latitude;
    }

    public void setSpeed(String speed){
        this.speed = speed;
    }

    public void setTimestamp(String timestamp){
        this.timestamp = timestamp;
    }
}

我已经创建了我的 SQLite 模型

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "speeds";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(Record.CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + Record.TABLE_NAME);

        onCreate(db);
    }

    public void insertRecord(String longitude, String latitude, String speed){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(Record.COLUMN_LONGITUDE, longitude);
        values.put(Record.COLUMN_LATITUDE, latitude);
        values.put(Record.COLUMN_SPEED, speed);

        System.out.println("VALUEEEEEEEES" + values);

        db.insert(Record.TABLE_NAME, null, values);
        db.close();
    }

    public List<Record> getAllRecords(){
        List<Record> records = new ArrayList<>();

        String selectQuery = "SELECT * FROM " + Record.TABLE_NAME + " ORDER BY " + Record.COLUMN_TIMESTAMP + " DESC";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if(cursor.moveToFirst()){
            do{
                Record record = new Record();
                record.setId(cursor.getInt(cursor.getColumnIndex(Record.COLUMN_ID)));
                record.setLongitude(cursor.getString(cursor.getColumnIndex(Record.COLUMN_LONGITUDE)));
                record.setLatitude(cursor.getString(cursor.getColumnIndex(Record.COLUMN_LATITUDE)));
                record.setSpeed(cursor.getString(cursor.getColumnIndex(Record.COLUMN_SPEED)));
                record.setTimestamp(cursor.getString(cursor.getColumnIndex(Record.COLUMN_TIMESTAMP)));

                records.add(record);
            } while (cursor.moveToNext());
        }
        db.close();

        return records;
    }

    public List<Record> getLastTenRecords(){
        List<Record> records = new ArrayList<>();

        String selectQuery = "SELECT * FROM " + Record.TABLE_NAME + " ORDER BY " + Record.COLUMN_TIMESTAMP + " DESC LIMIT 10";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if(cursor.moveToFirst()){
            do{
                Record record = new Record();
                record.setId(cursor.getInt(cursor.getColumnIndex(Record.COLUMN_ID)));
                record.setLongitude(cursor.getString(cursor.getColumnIndex(Record.COLUMN_LONGITUDE)));
                record.setLatitude(cursor.getString(cursor.getColumnIndex(Record.COLUMN_LATITUDE)));
                record.setSpeed(cursor.getString(cursor.getColumnIndex(Record.COLUMN_SPEED)));
                record.setTimestamp(cursor.getString(cursor.getColumnIndex(Record.COLUMN_TIMESTAMP)));

                records.add(record);
            } while (cursor.moveToNext());
        }
        db.close();

        return records;
    }
}

现在,我试图在 ExpandableListView 中显示一些数据。在我的场景中,我按 COLUMN_TIMESTAMP 对 sql 查询的响应进行排序并尝试以 HashMap<String , List<String> 的类型解析它为了 ExpandableListView来识别它。

问题是,即使结果已经排序了(循环打印时我可以看到它),当我使用这个方法解析并放入HashMap后,排序就消失了。

public static HashMap<String, List<String>> getLastTenData(Context context) {
        HashMap<String, List<String>> expandableListDetail = new HashMap<>();

        DatabaseHelper databaseHelper = new DatabaseHelper(context);

        List<Record> recordList = databaseHelper.getLastTenRecords();
        for(int i=0; i<recordList.size(); i++){
            List<String> myList = new ArrayList<>();
            myList.add("Y: "+recordList.get(i).getLatitude());
            myList.add("X: " + recordList.get(i).getLongitude());
            myList.add("Km/h: "+recordList.get(i).getSpeed());
            expandableListDetail.put(recordList.get(i).getTimestamp(), myList);
            System.out.println("check "+String.valueOf(i)+"    "+recordList.get(i).getTimestamp());
        }

        System.out.println(expandableListDetail);

        return expandableListDetail;
    }

我的意思是expandableListDetail应该按键排序却没有按键排序。 有什么帮助吗?

最佳答案

如果已经回答过类似的问题(关于HashSet)here

类似地,HashMap 是无序的,因此向其中添加值然后迭代映射不会按照您最初添加的顺序生成项目。

为什么LinkedHashMap可以解决这个问题? (从@Deadpool 那里得到了这个想法)

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

为什么TreeMap可以解决这个问题? (从@tomgeraghty3 获取这个想法)

The map is sorted according to the natural ordering of its keys

关于java - 插入到 HashMap 中会导致排序困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58983223/

相关文章:

java - 如果 equals 和 hashcode 比较 hashmap 中的不同值怎么办?

java - 我如何处理带计数的 ArrayList,并按函数分组

java - 通过浏览器运行服务时,config、properties 文件不会实时更新

java - 即使按钮禁用,MediaPlayer 也会继续播放

android - 如何点击外部链接打开特定应用程序的特定 Activity ?

java - 在 Java Android 应用程序中打开最后一个 fragment View

java - ConcurrentHashMap 在我的 Java Web 应用程序中陷入无限循环?

java - Vaadin 组件样式困惑

java - JAXB错误: Invalid byte 1 of 1-byte UTF-8 sequence的解释

java - Android:Android 应用程序中的所有 Activity 是在同一个线程中运行还是在它们自己的单独线程中运行?