TreeSet,Hashset,Set集合转为整型数组
生活随笔
收集整理的這篇文章主要介紹了
TreeSet,Hashset,Set集合转为整型数组
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
TreeSet,Hashset,Set集合轉(zhuǎn)為整型數(shù)組
? ? 【尊重原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處】http://blog.csdn.net/guyuealian/article/details/50990663 ? ? ?TreeSet集合轉(zhuǎn)為整型數(shù)組,Hashset集合轉(zhuǎn)為整型數(shù)組,Set集合轉(zhuǎn)為整型數(shù)組的方法類似: ? ? ?方法1:采用toArray(new Integer[] {})方法直接轉(zhuǎn)為Integer數(shù)組,然后再轉(zhuǎn)為整型數(shù)組; import java.util.Set; import java.util.TreeSet; public class JavaTest1 {public static void main(String args[]) {Set<Integer> allSet = new TreeSet<Integer>();allSet.add(3);allSet.add(2);allSet.add(1);allSet.add(4);// Object[] num1 = allSet.toArray();int[] num = SetToInt(allSet);for (int j = 0; j < num.length; j++) {System.out.print(num[j] + " ");}}// 將set集合轉(zhuǎn)為整型int數(shù)組的方法private static int[] SetToInt(Set<Integer> allSet) {// 先將set集合轉(zhuǎn)為Integer型數(shù)組Integer[] temp = allSet.toArray(new Integer[] {});//關(guān)鍵語(yǔ)句// 再將Integer型數(shù)組轉(zhuǎn)為int型數(shù)組int[] intArray = new int[temp.length];for (int i = 0; i < temp.length; i++) {intArray[i] = temp[i].intValue();}return intArray;} }? ? ?方法2:也可以使用toArray()方法直接轉(zhuǎn)為Object對(duì)象數(shù)組,然后再逐個(gè)轉(zhuǎn)為整型數(shù)組:import java.util.Set; import java.util.TreeSet; public class JavaTest1 {public static void main(String args[]) {Set<Integer> allSet = new TreeSet<Integer>();allSet.add(3);allSet.add(2);allSet.add(1);allSet.add(4);Object[] obj = allSet.toArray();//先講set集合轉(zhuǎn)為Object對(duì)象數(shù)組(向上轉(zhuǎn)型)int temp[] = new int[obj.length];for (int i = 0; i < obj.length; i++) {temp[i] = (int) obj[i];//將Object對(duì)象數(shù)組轉(zhuǎn)為整型數(shù)組(強(qiáng)制向下轉(zhuǎn)型)System.out.print(temp[i] + " ");}} }
如果你覺得該帖子幫到你,還望貴人多多支持,鄙人會(huì)再接再厲,繼續(xù)努力的~
總結(jié)
以上是生活随笔為你收集整理的TreeSet,Hashset,Set集合转为整型数组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: String内容不能改变的理解 Stri
- 下一篇: 2016年华为校招上机考试试题答案