12.18集合作业2

/*在一个列表中存储以下元素:apple,grape,banana,pear
3.1 返回集合中的最大的和最小的元素
3.2 将集合进行排序,并将排序后的结果打印在控制台上 [必做题]
*/

ublic class Text implements Comparable<Text>{
	private String name;

	@Override
	public String toString() {
		return "Text [name=" + name + "]";
	}

	public Text() {
		super();
		
	}

	public Text(String name) {
		super();
		this.name = name;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Text other = (Text) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public int compareTo(Text o) {
		
		return this.name.compareTo(o.name);
	}
	     

}

package Work10;

import java.util.ArrayList;
import java.util.Collections;import java.util.Comparator;

import javademo10.AgeComparator;
import javademo10.IdComparator;
import javademo10.Student;

public class Text1 {public static void main(String[] args) {
	  Text a1 = new  Text("apple");
	  Text a2 = new  Text("grape");
	  Text a3 = new  Text("banana");
	  Text a4 = new  Text("pear");
	 ArrayList<Text> p  = new  ArrayList<>();
	 p.add(a1);
	 p.add(a2);
	 p.add(a3);
	 p.add(a4);
	 Text max = Collections.max(p);
	 System.out.println(max);
	 Text l = Collections.max(p,new Text3Comparator());
	 System.out.println(l);
	 Text h = Collections.min(p,new Text3Comparator());
	 System.out.println(h);
	 Collections.sort(p, new Text3Comparator());
	 System.out.println(p);
	 
	  
}

}

package Work10;

import java.util.Comparator;

public class Text3Comparator implements Comparator<Text> {

	@Override
	public int compare(Text o1, Text o2) {
		
		return o1.getName().compareTo(o2.getName());
	}
	

}

你可能感兴趣的:(12.18集合作业2)