CrazyJava

本文介绍了Java编程的基础知识,包括数据类型、数组、对象和类的使用。讲解了如何创建和操作数组,以及字符串、对象的创建方式。此外,还提到了对象的序列化与反序列化、输入输出流的读写以及反射机制的应用。内容涵盖从简单的变量声明到复杂的数据结构和面向对象编程概念,是理解Java编程的良好起点。
摘要由CSDN通过智能技术生成

可在百度文库中搜索:疯狂java讲义全知识点笔记摘录。

Data Type
1.//change the char to the int directly
//Notice :the char use ‘ ’,the String use ” ”
char ch=‘c’;
Int cValue=ch;
2.“c:\codes”should be written as “c:\codes”
3.boolean can only be true or false; cannot be other numbers
4.—>String s0=“hello”;
—>String s1=“hello”;
—>String s2=“hel”+”lo”
—>System.out.println(s0s1);
—>System.out.println(s1
s2);
<—true
<—true
5.java 创建对象的常见方式:
@1.通过new调用构造器创建java对象;
@2.通过class对象的newInstance()方法调用构造器创建java对象;
@3.通过java的反序列化机制从IO流中恢复Java对象;
@4.通过java对象提供的clone()方法复制一个新的Java对象;
@5.除此之外,对于字符串以及Byte,Short,Integer,Long,Character,Float,Double,Boolean这些基本类型的包装类,Java还允许以直接量的方式来创建Java对象,列入如下语句:
String str=“ABC”;等
除此之外,通过简单的算术表达式,连接运算来创建Java对象,列入如下语句:
String str2=“ABC”+“efg”;

Array
1.one array can only have one type of object (not only can save data). in it.when array has been seated ,it size cannot be change.
Even if the object int it has been cleaned out ,the array still here and it size not change too.Array is a reference.
2.static origin the array
type[] arrayName=new type[]{element1,element2,……};
Can also write like:
type[] arrayName={element1,element2,….};
Dynamic origin the array
type[] arrayName=new type[size];
3.when you want to find a object which out of the bound of the array
You will see a statement as below:
Java.lang.ArrayIndexOutOfBoundsException:N
(N is where you want to find)
4.use array.length
public class Test {
public static void main(String[] args) {
String[] book=new String[4];
book[0]=“miki”;
book[1]=“lucy”;
for(int i=0;i<book.length;i++) {
System.out.println(book[i]);
}
}
}
<——miki
<—-Lucy
<—-null
<—-null
5.foreach(do not need the array’s size and index,can search all elements ,useful in array and set or map….,Notice: do not define the object in this foreach function ,it will cause trouble)
public class Test {
public static void main(String[] args) {
String[] books=new String[] {
“Miki”,
“Lucy”,
“Bob”
};
for(String book:books) {
System.out.println(book);
}
}
}
<——Miki
<——Lucy
<——Bob

6.when we define the elements in the foreach ,the iterator is temprenality, the system give the element to the temprenality data, the old element not change

public class Test {
public static void main(String[] args) {
String[] books=new String[] {
“Miki”,
“Lucy”,
“Bob”
};
for(String book:books) {
book=“Pipi”;
System.out.println(book);
}
System.out.println(books[0]);
}
}
<——Pipi
<—Pipi
<—Pipi
<—Miki
7.the real array object is in the heap memory, the reference array is in the stack memory.when there is no reference array reference to a real array object ,the real array object will be garbage collection collected, when array=null, it will be collect.

8.when a method has been action ,it will build a stack memory for itself. when method end ,the stack memory will end too.
The method inner variable will be put in the stack.when we
create a object ,the variable int the object will be save in a running data space which is a heap memory to let we use it in the next time, which would not be deleted when the method is end .when there is no reference to the object, the collector will collect it.
9.reference array(use reference to reference the object)
public class Test {
public static void main(String[] args) {
Person[] student=new Person[3];
Person zhang=new Person(18,“zhang”);
Person wang=new Person(20,“wang”);
student[0]=zhang;
student[2]=wang;
student[0].info();
}

}
class Person{
public int age;
public String name;

public Person(int age, String name) {
	super();
	this.age = age;
	this.name = name;
}

public void info() {
	System.out.println("name:"+name+",age:"+age);
}

}
<——name:zhang,age:18

10.basic array( the data save in the array directly )
public class Test {
public static void main(String[] args) {
int[] iArr=new int[] {
2,3,4,5,6,6
};
for(int i:iArr) {
System.out.print(i);
}
}

}
Oriented Object

1.this(“this” have two situations :@1.when in the constructors, it reference to the object which the constructor is originating.
@2.when in a method ,it reference to the object which is using the method now . @3.when inner a method has a variable as same as a Field ,you can use “this ”,to get the Field.)
For example :we write a code to let the dog run and jump:
public class Dog {
public void jump() {
System.out.println(“jumping”);
}
public void run() {
Dog d=new Dog();
d.jump();
System.out.println(“running”);
}
}
public class DogTest {
public static void main(String[] args) {
Dog d=new Dog();
d.run();
}
}
<——jumping
<——running
//the code can run but it not really good ,we need not build two dog object ,because there is only one dog which is running and jumping.
//the good code as below :
public class Dog {
public void jump() {
System.out.println(“jumping”);
}
public void run() {
this.jump();
System.out.println(“running”);
}
}

public class DogTest {
public static void main(String[] args) {
Dog d=new Dog();
d.run();
}
}

<——jumping
<——running
//the code also can write as below :
public class Dog {
public void jump() {

	System.out.println("jumping");
}
public void run() {
	jump();//there can without use “this”,because we use it as default
	System.out.println("running");
}

}

public class DogTest {
public static void main(String[] args) {
Dog d=new Dog();
d.run();
}
}

<——jumping
<——running

2.use private Field and the getter and setter method to closure or package the the Field which you do not want other to directly modify.
For example(suit JAVABEAN):
public class Person {
private String name;
private int age;

public String getName() {
	return name;
}
public void setName(String name) {
	if(name.length()>6) {
		System.out.println("wrong");
		return;
	}else {
	this.name = name;
	}
}
public int getAge() {
	return age;
}
public void setAge(int age) {
	if(age>100||age<0) {
		System.out.println("wrong");
		return;
	}else {
	this.age = age;
	}
}

}

3.because in Derived the tag is private, so the system will find Derived’s parent “Parent”,so if you want to use tag, you should change the type of the d.tag by yourself.When we build a child object ,in the memory we also build it parent ’s Field .if the child and the parent has the same Field the memory will help them build both Field ’s memory.just the child has override the parent’s but the parent’s still have.you can use the “super” to call it.
public class Parent {
public String tag=“mama”;
}
class Derived extends Parent{
private String tag=“papa”;
}
public class myTest {
public static void main(String[] args) {
Derived d=new Derived();
System.out.println(d.tag);//wrong
System.out.println(((Parent)d).tag);//right
}
}

4.use “parseXxx(String s)”to let String type to become Xxx type
For example(String to Xxx):
String intStr=“123”;
int i =Integer.parseInt(intStr);@1
Int i =new Integer(intStr);@2
@1 as same as @2;
For example(Xxx to String):
String ftStr=String.valueOf(2.13f);
Or method :
String ftStr=2.13f+” ”;

5.use a array as cache pool to cacheImmutale:
class CacheImmutale {
private static int MAX_SIZE=10;
// cache object by using array
private static CacheImmutale[] cache=new CacheImmutale[MAX_SIZE];
// record the object is in which place in the cache,the newest oject is in the cache[pos-1]
private static int pos=0;
private final String name;
private CacheImmutale(String name) {
this.name=name;
}
public String getName() {
return name;
}
// loop the object which has been cached,the find the object with the specific name where it is
public static CacheImmutale valueOf(String name) {
for(int i=0;i<MAX_SIZE;i++) {
// if has the same object return it directly
if(cache[i]!=null&&cache[i].getName().equals(name)) {
return cache[i];
}
}
// cache pool fulled
if(pos==MAX_SIZE) {
// overwrite the first postion’s object
cache[0]=new CacheImmutale(name);
pos=1;
}
else {
// save the new object
cache[pos++]=new CacheImmutale(name);
}
return cache[pos-1];
}

// override equals()
public boolean equals(Object obj) {
if(this==obj) {
return true;
}
if(obj!=null&&obj.getClass()CacheImmutale.class) {
CacheImmutale ci=(CacheImmutale)obj;
return name.equals(ci.getName());
}
return false;
}
//overwrite hashCode();
public int hashCode() {
return name.hashCode();
}
}
public class CacheImmutaleTest{
public static void main(String[] args) {
CacheImmutale c1=new CacheImmutale.valueOf(“hello”);
CacheImmutale c2=new CacheImmutale.valueOf(“hello”);
System.out.println(c1
c2);
}
}

<——true

6.abstract(Notice:absract class can’t build object ,only can be regard as a parents class tone extends, so it can not use itself ’s constructor):
public abstract class Shape {
{
System.out.println(“origianl the Shape”);
}
private String color;
public abstract double calPerimeter();
public abstract String getType();
public Shape() {};
public Shape(String color) {
this.color=color;
}

public static void main(String[] args) {
	Shape triangle=new Triangle("red",2,3,4);
	Shape circle=new Circle("blue",3);
	System.out.println(circle.color);
	System.out.println(triangle.calPerimeter());
}

}
class Triangle extends Shape{
private double a;
private double b;
private double c;
public Triangle(String color,double a,double b, double c) {
super(color);
this.setSides(a, b, c);
}
public void setSides(double a,double b, double c) {
if(a>=b+c||b>=a+c||c>=a+b) {
System.out.print(“is not a triangle”);
return;
}
this.a=a;
this.b=b;
this.c=c;

}
public double calPerimeter() {
	return a+b+c;
}
public String getType() {
	return "triangle";
}

}
class Circle extends Shape{
private double radius;
public Circle(String color,double radius) {
super(color);
this.radius=radius;
}
public Circle() {

}
public double calPerimeter() {
	return 2*radius*Math.PI;
}
public String getType() {
	return "circle";
}

}

<——origianl the Shape
<——origianl the Shape
<——blue
<——9.0

7.interface:
interface Product {
int getProduceTime();
}
interface Output{
int MAX_CACHE_LINE=50;
void out();
void getData(String msg);
}

public class Printer implements Product,Output{
private String[] printData=new String[MAX_CACHE_LINE];
// the number of the data which we now should print
private int dataNum=0;
public void out() {
while(dataNum>0) {
System.out.println(“print the data”+printData[0]);
System.arraycopy(printData, 1, printData, 0, --dataNum);
}
}
public void getData(String msg) {
if(dataNum>=MAX_CACHE_LINE) {
System.out.println(“failed”);
}
else {
printData[dataNum++]=msg;
}
}
public int getProductTime() {
return 45;
}
public static void main(String[] args) {
Output o=new Printer();
o.getData(“hihi”);
o.getData(“kiki”);
o.out();
Product p=new Printer();
System.out.println(p.getProduceTime());
Object obj=p;

}

}

<———print the datahihi
<———print the datakiki

//Now we use designer Module to improve the code :
//Below are Simple Factory Module
public class Computer {
private Output out;
public Computer(Output out) {
this.out=out;
}
public void keyIn(String msg) {
out.getData(msg);
}
public void print() {
out.out();
}
}
public class OutputFactory {
public Output getOutput(){
return new Printer();
}
public static void main(String[] args) {
OutputFactory of=new OutputFactory();
Computer c=new Computer(of.getOutput());
c.keyIn(“my”);
c.keyIn(“you”);
c.print();
}
}
<——print the datamy
<——print the datayou

When we want to choose a betterPrinter,we only should change the blue line of the code
public class Printer implements Product,Output{
private String[] printData=new String[MAX_CACHE_LINE];
// the number of the data which we now should print
private int dataNum=0;
public void out() {
while(dataNum>0) {
System.out.println(“print the data”+printData[0]);
System.arraycopy(printData, 1, printData, 0, --dataNum);
}
}
public void getData(String msg) {
if(dataNum>=MAX_CACHE_LINE*2) {
System.out.println(“failed”);
}
else {
printData[dataNum++]=msg;
}
}
public int getProductTime() {
return 45;
}
}

public class OutputFactory {
public Output getOutput(){
return new betterPrinter();
}

8.Command Module:
public interface Command {
void proccess(int [] target);
}
//management the all command
public class ProcessArray {
public void process(int[] target,Command cmd) {
cmd.proccess(target);
}
}
public class PrintCommand implements Command{

public void proccess(int[] target) {
		for(int i:target) {
			System.out.println(i);
		}
}

}
public class AddCommand implements Command{

public void proccess(int[] target) {
	int sum=0;
	for(int i:target) {
		sum+=i;
	}
	System.out.println(sum);
}

}

public class CommandTest{
public static void main(String[] args) {
ProcessArray pa=new ProcessArray();
int[] target= {1,2,3,4};
pa.process(target, new PrintCommand());
System.out.println("------------------");
pa.process(target, new AddCommand());
}
}
<———1
<——2
<——3
<——4

<——10

9.Anonymous(when you only need to build a class and you only use it at one time you can build a a anonymous.if you should use it for many times, you should build the class independently.when the anonymous class extends to a abstract class or a parents class ,you can build a anonymous class with variable in constructor; if not you can only use the constructor without variable.Notice :you only can build anonymous when it extend sth.):
For example@1(implements from a interface to new a anonymous class ,so you only can use constructor without variable ):
interface Product{
public double getPrice();
public String getName();
}

public class AnonymousTest {
public void test(Product p) {
System.out.println("I have buy “+p.getName()+” using "+p.getPrice() );
}
public static void main(String[] args) {
AnonymousTest at=new AnonymousTest();
at.test(new Product() {
public double getPrice() {
return 888.0;
}
public String getName() {
return “hat”;
}
});
}
}

<——I have buy hat using 888.0
For example@2 (this method ’s result is the same as @1):
class AnonymousProduct implements Porduct{
public double getPrice() {
return 888.0;
}
public String getName() {
return “hat”;
}
}
at.test(new AnonymousProduct());

For example@3(new a anonymous which can use constructor, because the class which it new has a constructor which as variable in it):
import java.nio.charset.MalformedInputException;

abstract class Device{
private String name;
public abstract double getPrice();
public Device() {}
public Device(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

public class AnonymousInner {
public void test(Device d) {
System.out.println("I have buy “+d.getName()+” price: "+d.getPrice());
}
public static void main(String[] args) {
AnonymousInner ai=new AnonymousInner();
ai.test(new Device(“hat”) {
public double getPrice() {
return 999.0;
}
});
Device d=new Device() {
public double getPrice() {
return 789.0;
}

	public String getName() {
		return "shoes";
	}
};
ai.test(d);

}
}
<——I have buy hat price: 999.0
<——I have buy shoes price: 789.0

10.Closure and callBackReference
interface Teachable{
void work();

}

public class Programmer {
private String name;

public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
public Programmer() {}
public Programmer(String name) {
	this.name=name;
}
public void work() {
	System.out.println("programming");
}

}

public class TeachableProgrammer extends Programmer {
public TeachableProgrammer() {}
public TeachableProgrammer(String name) {
super(name);
}

public void teach() {
	System.out.println(getName()+"is teaching");
}
private class Closure implements Teachable{
	public void work() {
		teach();
	}
}
public Teachable getCallBackReference() {
	return new Closure();
}

}
public class TeachableProgrammerTest {
public static void main(String[] args) {
TeachableProgrammer tp=new TeachableProgrammer("kiki ");
tp.work();
tp.getCallBackReference().work();
}
}

11.Enum:
public enum Gender {
MALE,FAMALE;
private String name;
public void setGender(String name) {
switch(this) {
case MALE:
if(name.equals(“man”)) {
this.name=name;
}else {
System.out.println(“erro”);
return;
}
break;
case FAMALE:
if(name.equals(“woman”)) {
this.name=name;
}else {
System.out.println(“erro”);
return;
}
break;
}
}
public String getName() {
return this.name;
}
}

public class GenderTest {
public static void main(String[] args) {
// write Gender 's switch to check if you have set the right Gender or not ;
// if not you will get a return wrong;

	Gender g=Enum.valueOf(Gender.class, "MALE");
	g.setGender("man");
	System.out.println(g+"represent:"+g.getName());
	
}

}

//now we use the constructor to set enum:
public enum Gender {
MALE(“man”),FEMALE(“woman”);
private String name;
// private the constructor
private Gender(String name) {
this.name=name;
}
public String getName() {
return this.name;
}

}

Above is the same as below :
private static final Gender MALE=new Gender(“man”);
private static final Gender FEMALE=new Gender(“woman”);

12.Rubbish Collection(you can call it actively but we can not forced java to collection it surely):
@1:System.gc()
@2:Runtime.getRuntime().gc()

Collection
1.in a array you can save basic data and object’s reference, but in the collection you can only save object’s reference
2.Collection and Map are interface, and in collection also have child interface:set, queue,list.and they have realized class:eg.HashSet,TreeSet,ArrayList,ArrayDeque,LinkedList,HashMap,TreeMap.
3.Set:no order, can not repeat;List:has order,can repeat ,different from array, because array’s size can not change, but List’s size can change;
Map:has key-value.
4. In the array you can only add the same type object, but in the Collection you can put different type object’s reference in it.because the are all “object”type, but if you do not want all object add in it ,you can use Generic Type; and you can add basic data type ,because Java has already help you automatically package it as object(eg:int—>Integer).
5.Iterator:
@1.boolean hasNext();
@2.Object next();
@3.void remove();
//below are use iterator to search the Collection
public class IteratorTest {
public static void main(String[] args) {
Collection books=new HashSet();
books.add(“jiji”);
books.add(“hihi”);
Iterator it=books.iterator() ;
while(it.hasNext()) {
// it.next() will return "Object"Type
// so you should change the type by youself
String book=(String)it.next();
System.out.println(book);
if(book.equals(“jiji”)) {
// delete the last next()'s return elements
it.remove();//right
// use the Collection remove when it is iteratoring,will cause java.util.ConcurrentModificationException
books.remove(book);//wrong
}
//interator not use the collection itself, it only give you the collection’s elements ’s data ,so you can not give a data to a iterator elements;
book="gigi”;//you will succeed to do it
}
System.out.println(books);

	}

}

6.foreach:(use foreach to search the Collection)
import java.util.Collection;
import java.util.HashSet;

public class ForeachTest {
public static void main(String[] args) {
Collection books=new HashSet();
books.add(“jiji”);
books.add(“ftft”);
books.add(“popo”);

	for(Object obj:books) {

// here the book also not the elements itself ,it only the data of the elements
// so if you cahne the data of the elements in the loop has no meaning
String book=(String)obj;
System.out.println(book);
if(book.equals(“jiji”)) {
// here you can not use Collection’s remove() Method too, will has ConcurrentModificationException;
books.remove(book);
}
}
System.out.println(books);
}
}
<——popo
<—ftft
<—jiji
<—[popo, ftft]

6.HashSet(use the hash code to choose where to save the elements,so you don’t know where it real save ,it not save by you add order .in the eclipse I test and think it just as a stack when you add sth.at first, when you print the HashSet ,it will be printed out at last, FILO):
import java.util.HashSet;
import java.util.Iterator;

class R{
int count;
public R(int count ) {
this.count=count;
}
public String toString() {
return “R[count:”+count+"]";
}
public boolean equals(Object obj) {
if(obj==this) {
return true;
}
if(obj!=null&&obj.getClass()R.class) {
R r=®obj;
if(r.count
this.count) {
return true;
}
}
return false;
}
public int hashCode() {
return this.count;
}
}

public class HashSetTest {
public static void main(String[] args) {
HashSet hs=new HashSet();
hs.add(new R(5));
hs.add(new R(4));
hs.add(new R(3));
System.out.println(hs);
Iterator it=hs.iterator();
R first=® it.next();
first.count=5;
System.out.println(hs);
hs.remove(new R(5));
System.out.println(hs);
System.out.println(“does hs contains the object which the data is 3?”+hs.contains(new R(5)));
System.out.println(“does hs contains the object which the data is 5?”+hs.contains(new R(3)));

}

}
[R[count:3], R[count:4], R[count:5]]
[R[count:5], R[count:4], R[count:5]]
[R[count:5], R[count:4]]
does hs contains the object which the data is 3?false
does hs contains the object which the data is 5?false

//above is because of the programmer at first remove the elements which the hash and the equals()is all right to the new R(5),but then the programmer cannot find a elements which the hash and the equals()is all fit the condition,so it return false

7.LinkedHashSet(use Link Chain and it add by order, it print by you add order, and although it use linked chain but it still Set so you can not add same elements):
public class LinkedHashSetTest {
public static void main(String[] args) {
LinkedHashSet books=new LinkedHashSet();
books.add(“hihi”);
books.add(“bobo”);
System.out.println(books);
books.remove(“hihi”);
books.add(“hihi”);
System.out.println(books);
}
}

[hihi, bobo]
[bobo, hihi]

8.TreeSet(the realize class for SortedSet Interface,this Set has been default sorted by small to big, how to use it see example:)
For example:
import java.util.TreeSet;

public class TreeSetTest {
public static void main(String[] args) {
TreeSet nums=new TreeSet();
nums.add(-2);
nums.add(8);
nums.add(4);
nums.add(-1);
System.out.println(nums);
System.out.println(nums.first());
System.out.println(nums.last());
// include the (elements) itself
System.out.println(nums.headSet(5));
System.out.println(nums.tailSet(-1));

	System.out.println(nums.subSet(2, 8));
	System.out.println(nums.lower(4));
	System.out.println(nums.higher(2));
}

}

[-2, -1, 4, 8]
-2
8
[-2, -1, 4]
[-1, 4, 8]
[4]
-1
4
//the TreeSet has comparable interface ,if you add a class’s object in it ,the add elements should be the same class ,and it also should has realized the compared interface ,ig not ,it will became ClassCatException.And the method to identify weather the too elements is same by identifying compareTo(Object obj) is return “0”or not ,if(0),they are same ,if not(0),they are different.
For example(try not let other’s to modify the object’s attributes ):
import java.util.TreeSet;

class R implements Comparable{
int count;
public R(int count) {
this.count=count;
}
public String toString() {
return “R[:”+count+"]";
}
public boolean equals(Object obj) {
if(obj==this) {
return true;
}
if(obj!=null&&obj.getClass()R.class) {
R r=®obj;
if(r.count
this.count) {
return true;
}
}
return false;
}

public int compareTo(Object obj) {
	R r=(R)obj;
	return count>r.count? 1:
		     count<r.count?  -1:0;
}

}

public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add(new R(5));
ts.add(new R(8));
ts.add(new R(-1));
ts.add(new R(3));
System.out.println(ts);
R first =®ts.first();
first.count =20;
R last=®ts.last();
last.count=-2;
// now yu will see that the treeSet are not by order,so if we add sth. i the treeSet,the add object’s attribute should not easy to be change
System.out.println(ts);
// now we try to delete the elements which has been changed
System.out.println(ts.remove(new R(-2)));
System.out.println(ts);
// now we try ti delete the elements which not been changed
System.out.println(ts.remove(new R(5)));
System.out.println(ts);

}

}

[R[:-1], R[:3], R[:5], R[:8]]
[R[:20], R[:3], R[:5], R[:-2]]
false
[R[:20], R[:3], R[:5], R[:-2]]
true
[R[:20], R[:3], R[:-2]]

9.TreeSet’s Comparator interface && compare(Object o1,Object o2)
For example:
import java.util.Comparator;
import java.util.TreeSet;

class M{
int age;
public M(int age) {
this.age=age;
}
public String toString() {
return “M[age:”+age+"]";
}
}

public class TreeSetTest {
public static void main(String[] args) {
TreeSet ts=new TreeSet(new Comparator() {
// base on M’age to compare big or small
public int compare(Object o1,Object o2) {
M m1=(M)o1;
M m2=(M)o2;
return m1.age>m2.age? -1 :
m1.age<m2.age? 1:0;
}
});
ts.add(new M(5));
ts.add(new M (-1));
ts.add(new M(8));
System.out.println(ts);

}

}

[M[age:8], M[age:5], M[age:-1]]

10.EnumSet:
For example:
import java.util.Collection;
import java.util.EnumSet;
import java.util.HashSet;

enum Season{
SPRING,SUMMER,FALL,WINTER;
}

public class EnumSetTest {
public static void main(String[] args) {
// EnumSet don not have constructor ,so you should use below method to create a EnumSet
// below are all enum are EnumSet’s elements
EnumSet es1=EnumSet.allOf(Season.class);
System.out.println(es1);
// create a empty EnumSet
// and you choose which enum to want to add in the EnumSet,so you should write EnumSet.noneOf(EnumWhichYouWantToAdd.class)
EnumSet es2=EnumSet.noneOf(Season.class);
System.out.println(es2);
// add too EnumSet elements by youself
// when you add different elements you should sure that they are the same type
es2.add(Season.WINTER);
es2.add(Season.SPRING);
// now Notice the print order
System.out.println(es2);
// now we use the enum data to create a EnumSet
// because EnumSet are also Set so we can not add a same elements twice times
EnumSet es3=EnumSet.of(Season.SUMMER,Season.SUMMER);
System.out.println(es3);
// now we can create a EnumSet which from one enum to the other enum
EnumSet es4=EnumSet.range(Season.SPRING, Season.FALL);
System.out.println(es4);
// now we create a EnumSet es5 which add es4 will became a whole enum
EnumSet es5=EnumSet.complementOf(es4);
System.out.println(es5);
// now we use Collection to create a EnumSet
Collection c=new HashSet();
c.clear();
c.add(Season.FALL);
c.add(Season.SUMMER);
// now we copy the collection to EnumSet
EnumSet es6=EnumSet.copyOf©;
System.out.println(es6);
// below code will cause ClassCastException
// because they are now add String not the Enum we has already add
c.add(“hihi”);
c.add(“gugu”);
es6.copyOf©;
System.out.println(es6);

}

}

[SPRING, SUMMER, FALL, WINTER]
[]
[SPRING, WINTER]
[SUMMER]
[SPRING, SUMMER, FALL]
[WINTER]
[SUMMER, FALL]
Exception in thread “main” java.lang.ClassCastException: java.base/java.lang.String cannot be cast to java.base/java.lang.Enum
at java.base/java.util.EnumSet.copyOf(EnumSet.java:176)
at cn.My.EnumSetTest.main(EnumSetTest.java:48)

11.HashSet:easy to get
TreeSet:has order
LinkedHashSet:easy to search one by one
EnumSet:good,but it can only set the same enum

12.List(has order, can repeat, has index,like array but can change the size):
In the List you can use for loop to search the List
For example:
for(int i=0;i<books.size();i++){
System.out.println(books.get(i));
}
Notice the elements in it are also Object,so you should change the type
//Queue Interface has Deque Interface,Deque has ArrayDeque and LinkedList Class.LinkesList are both Deque Interface and List Interface’s class
//List.ArrayList:can change the array size;
//Arrays.ArrayList:can not changed the size ,and can not use add()/remove()
Method,it will cause UnsupportedOperationException.

13.Map:
//Set entrySet():return the Set of all couple of key and value which Map contains, all elements in the Set is Map.Entry’s object (Entry is Interface Map’s inner class) .
//Set keySet():return a Set which contains all key in the Map.
//Object put(Object key, Object value):add key and value ,firstly we compare the key’shashcode ,if hashcode is different ,we put the key_value in the difference place in the table(table is where we put the Entry(which has constructor:Entry<K,V>(hash, key, value,e) ,e is the point which point to the old Entry))),if there has a same hashcode,we then compare the equals()is same we cover the old value, key will not change,but if the equals()is different we create a chain ,the new key-value use “e” to point to the old key -value,and when we find key-value to loop the chain the old one is always the last one to find, new one is always in the head of the chain. this is different from the hashSet,if there is a same hashCode ,it will build a chain to keep the new data.
//Colletcion values():return the Collection which contains all values
//Map’s inner class Entry :(has three method):
@1.Object getKey():return key
@2.Object getValue():return value
@3.Object setValue(V value):set value ,return new value
For example:
import java.util.HashMap;

//when you define a Class and you want use it inCollection .eg.HashMap.
//you should be sure that they has method equals() ;
//if it is HashMap or HashSet or Hashtable you should be sure they had method equals() and hashcode() ,and when you use both of them ,you sholud ensure that their return result will be the same

class A{
int count;
public A(int count) {
this.count=count;
}
public boolean equals(Object obj) {
if(obj==this) {
return true;
}
if(obj!=null&&obj.getClass()A.class) {
A a=(A)obj;
return a.count
this.count;
}
return false;
}
public int hashCode(){
return this.coun

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值