本帖最后由 aA772807986 于 2016-11-12 14:09 编辑
[Java] 纯文本查看 复制代码 package com.lxy.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class Test11 {
public static void main(String[] args) throws Exception{
List<Integer> list = new LinkedList<Integer>();
//读取文件 number.txt对应src目录的文件
BufferedReader reader=new BufferedReader(new InputStreamReader(Test11.class.getClassLoader().getResourceAsStream("./number.txt")));
String con;
while((con=reader.readLine())!=null){
list.add(Integer.valueOf(con));
}
reader.close();
list = noRepeat(list);// 去掉重复元素
// 放入数组
Integer[] iArray = list.toArray(new Integer[list.size()]);
iArray = sort(iArray);// 将数组从大到小排序
System.out.println("================================输出数组============================");
for (Integer i : iArray) {//输出数组
System.out.print(i + "\t");
}
System.out.println();
printList(list);// 打印集合
System.out.println();
}
// 将List集合去除重复元素
public static List noRepeat(List list) {
List myList = list;
if (myList != null) {
for (int i = 0; i < myList.size(); i++) {
for (int j = i + 1; j < myList.size(); j++) {
if (myList.get(i).equals(myList.get(j))) {
myList.remove(j);
}
}
}
}
return myList;
}
//打印集合
public static void printList(List list) {
System.out
.println("=========================遍历list 第一种方式for========================");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + "\t");
}
System.out
.println("\n=========================遍历list 第二种方式Iterator========================");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + "\t");
}
}
// 将数字进行排序
public static Integer[] sort(Integer[] array) {
Integer[] myArray = array;
for (int i = 0; i < myArray.length - 1; i++) {
for (int j = i + 1; j < myArray.length; j++) {
if (myArray[i] < myArray[j]) {
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
}
}
return myArray;
}
}
|