-2

我是编码 Android 的新手。我被投入到一个项目中,下面的代码可以工作,但我并不真正理解它,这并不能真正帮助我学习。有人会用每个阶段正在做什么来评论代码吗?

SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
        TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Log.i("map values", entry.getKey());

        }


      List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
            sortedByValue.add(e);
        }


     // Pair doesn't have a comparator, so you're going to need to write one.
        Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
            public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {

                String sls = String.valueOf(lhs.first);
                String srs = String.valueOf(rhs.first);
                int res = sls.compareTo(srs);
                // Sort on value first, key second
                return res == 0 ? lhs.second.compareTo(rhs.second) : res;
            }
        });

        for (Pair<Object, String> pair : sortedByValue) {
            Log.i("map values", pair.first + "/" + pair.second);
        }


      Collection<?> stringArrayList = keys.values();
      final CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);
4

1 回答 1

2
SharedPreferences myPrefs = this.getSharedPreferences("FileName", MODE_PRIVATE);
    TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
    for (Map.Entry<String, ?> entry : keys.entrySet()) {
        Log.i("map values", entry.getKey());

    }

在共享首选项文件中记录所有键值对。

List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
    for (Map.Entry<String, ?> entry : keys.entrySet()) {
        Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
        sortedByValue.add(e);
    }

将具有所有设置的 Map 转换为 List 进行排序

Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
        public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {

            String sls = String.valueOf(lhs.first);
            String srs = String.valueOf(rhs.first);
            int res = sls.compareTo(srs);
            // Sort on value first, key second
            return res == 0 ? lhs.second.compareTo(rhs.second) : res;
        }
    });

自定义比较器对 Pairs 列表进行排序。它比较值。如果它们相等,它会比较第二个值。

for (Pair<Object, String> pair : sortedByValue) {
        Log.i("map values", pair.first + "/" + pair.second);
    }

打印排序的首选项。

  Collection<?> stringArrayList = keys.values();
  final CharSequence[] prefsCharSequence = stringArrayList.toArray(new CharSequence[stringArrayList.size()]);

将 SharedPreferences 文件中的键转换为 Collection,然后将其转换为字符串列表。

于 2012-10-10T01:51:47.207 回答