怎样把list集合转换成set集合,但是有个条件,就是list集合里的顺序不能改变,set会自动排序,有可能把原来的顺序打乱了,我试着写了几种方法但没走通,各位有什么好方法吗?最好能贴一些看着很直观的代码。

解决方案 »

  1.   


    public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(2);list.add(3);list.add(1);
    Set<Integer> set = new LinkedHashSet<Integer>(list);
            System.out.println(set);
    }
      

  2.   


    /**
     * @param args
     */
    public static void main(String[] args) {
    List<String> list=new ArrayList<String>();
    list.add("hello");
    list.add("world");
    list.add("boy");
    list.add("me");
            System.out.println(list);
            
            Set<String> linkset=new LinkedHashSet<String>();
            linkset=new LinkedHashSet(list);
            System.out.println(linkset);
            
            Set<String> set=new HashSet<String>();
    set.add("hello");
    set.add("world");
    set.add("boy");
    set.add("me");
    System.out.println(set);
    }/*output
    [hello, world, boy, me]
    [hello, world, boy, me]
    [hello, me, boy, world]
    */
      

  3.   

    学习了...我没用过LinkedHashSet呵,据说是保留插入时的顺序
      

  4.   

    实现在set接口自己实现一个set子类再转换