有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java值在从ArrayList转换为ArrayAndroid时交换

我有一个ArrayList,它有一些元素。此列表中的项目将重复。我想将相似的值分组并将其转换为数组

目前我的ArrayList是:-

ArrayList<String> isonC = new ArrayList<String>();

isonC的值=`[a,a,a,b,c,c,c,c,c,d,d,d,d,d,d,d] 我认为:-

icons = isonC.toArray(new String[isonC.size()]);
icons = new HashSet<String>(Arrays.asList(icons)).toArray(new String[0]);

我得到的值如下:- 图标=[a, c, b,d]

鉴于元素的实际顺序应为:-

[a,b, c,d]

为什么第二和第三个值互换

任何建议都会有帮助。 谢谢


共 (2) 个答案

  1. # 1 楼答案

    尝试使用TreeSet而不是HashSet。请尝试以下方法:-

    TreeSet<String> mySet =  new TreeSet <String>(myArrayList);
    myArray =  mySet.toArray(new String[mySet.size()]);
    
  2. # 2 楼答案

    documentationLinkedHashSet

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    因此,假设您希望在oldArray中出现较早的项在newArray中出现较早,则以下操作应该可以工作:

    String[] newArray = new LinkedHashSet<String>(Arrays.asList(oldArray)).toArray(new String[0]);