The eighth chapter of the container

1. container refers to the "object can contain other objects" that argument, right?


Correct.


2.Collection / Set / List of Contact difference?


(1) Collection is a collection of top-level interface Java, a storage group is not unique, unordered objects;
(2) List interface and the interface is the Collections Set interface has two sub-interfaces;
(3) List store a set of interfaces is not unique, orderly Object (insertion order);
the set interface memory a set of unique, unordered objects;
(. 4) Collection, List, the set architecture diagram:

 

 

3.Set List and characteristics with the difference?

(. 1) List:
. 1) is ordered Collection, use this interface to accurately control the position of insertion of each element. Users can use the index to access the List no element
, which is similar to Java arrays.
2) Any method can be operated indexing method is unique interfaces List.

(2) the Set:
. 1) storing a set of unique interfaces, unordered objects (stored and retrieved sequentially do not necessarily match).
Method 2) is similar to the operation data and List, Set methods interfaces associated with the index does not exist.


[4] Collection machine interface common way to practice


add (Object obj): Add, object reference is stored;
size (): the actual number of elements in the container;
Remove (Object obj): removes an element;
removeAll (Collection c): c delete the set of elements like elements;
retainAll, (collection C): retaining only the current collection (set of calls this method) the set C (parametric method) of the same element;
the contains (Object obj): the presence or absence of elements obj determined set;
isEmpty (): determines whether the set is empty;
the iterator (): iterator that generates this collection;


5. [on board] the following code, the same effect? ​​Analysis of illustration.


Collection c = new HashSet ();
Code 1: c2.addAll (c) is set to [c] is added to the elements in the collection c2;

Collection c2 = new HashSet();
Apple a = new Apple();
c.add(a);
c2.addAll(c);

// add another container all the elements!

Code 2: c2.add (c) is added to [c] as a collection element c2 in the collection;

Collection c = new HashSet();
Collection c2 = new HashSet();
Apple a = new Apple();
c.add(a);
c2.add(c);


6. would like to take the intersection of two elements in a container, which method to use?

retainAll (Collection c): retaining only the current collection (set of calls this method) the set C (parameters for this method) in the same elements.

 

7. explain the role isEmpty, and explains the following code is the problem?


isEmpty (): determines whether the set is empty, i.e. the actual number of elements in the set is zero, whereby this method is called when that collection is occurring (
if the set does not exist, there are no empty or not a). To distinguish the collection is empty and there is no set of meanings is different.

The following code Collection c = null, c does not refer to any collection, i.e. no real set, call isEmpty () method of a null pointer exception occurs.
C = null Collection;
System.out.println (c.isEmpty ());

 

8. I would like to define an array. The array can be either put: Dog object, you can also put Cat objects, you can also put
Integer object, how the definition?


Code Example:


Object[] objArr=new Object[5];
objArr[0]=56;
objArr[1]=123;
objArr[2]="Hello world";
objArr[3]=newDog();
objArr[4]=newCat();


9.List interface adds some methods of operation associated with the order, and what the role of the two methods below is?


add (int index, E element) : the element is added to the index element index position;
GET (int index): to give an element index index.


What 10.ArrayList underlying use to achieve? LinkedList what is achieved?


See next question.


11. tell the difference ArrayLIst, LinkedList, Vector's.


ArrayLIst, both LinkedList implement the List interface, we have a List of elements in order, not only feature.
ArrayList implements variable length arrays allocated contiguous space in memory. Random access through the elements and the elements more efficient;

 

LinkedList linked list storage. Insert, delete elements when more efficient

 

Vector and ArrayList difference Contact: See 294 questions.

 

12. I have some data require frequent query, insert, and delete operations are very small, and there is no common thread between
sharing, better use List following which implementation class?


ArrayList. ArrayList implements variable length arrays allocated contiguous space in memory. Random access through the elements and the elements more efficient.


13. [machine] List of new methods for the relevant order of each test. And use debug
to help us understand the program run.


add (int index, Object obj) : added element obj at the specified index (index);
the addAll (int index, the Collections c): adding a set of c, all of the elements in the specified index (index);
Remove (int index): Delete index position for the index elements;
SET (int index, Object obj): use element obj replacement element on the specified index;
GET (int index): Get the element at the specified index position;
the subList (int the beginIndex, int endIndex): get a List object that contains the specified range of elements in the index.

 

14. Computer class definitions, usage price sort. (Using the Comparable interface)

 

(1) Computer defined class that implements the interface Comparable:
publicclass Computer implementsComparable {
privatedouble. Price; // private attributes;
// Constructors;
public Computer (Double. Price) {
Super ();
this.price. Price =;
}

//实现Comparable接口中的compareTo方法;
@Override
publicint compareTo(Object o) {
Computer c=(Computer)o;

if(this.price>c.price){
return 1;
}elseif(this.price<c.price){
return -1;
}else{
return 0;
}
}

//重写toString()方法;
@Override
public String toString() {
return"Computer [price=" + price + "]";
}

}

(2)加入TreeSet;
import java.util.Iterator;
import java.util.TreeSet;

publicclass Test {
publicstaticvoid main(String[] args) {
//创建TreeSet;
TreeSet<Computer> treeSet=new TreeSet<Computer>();

//创建Computer对象;
Computer computer1=new Computer(3000);
Computer computer2=new Computer(2650);
Computer computer3=new Computer(5878.8);
Computer computer4=new Computer(6000.78);

//将Computer对象加入到treeSet中;
treeSet.add(computer1);
treeSet.add(computer2);
treeSet.add(computer3);
treeSet.add(computer4);
//为treeSet创建迭代器;
Iterator<Computer> it=treeSet.iterator();
//遍历treeSet
while(it.hasNext()){
System.out.println(it.next());
}

}

}

Results: Sort realized price;
Computer [. Price = 2650.0]
Computer [. Price = 3000.0]
Computer [. Price = 5878.8]
Computer [. Price = 6000.78]


15.equals returns true, hashcode necessarily equal to it?


Yes

 

The difference 16.HashSet and TreeSet


HashSet:
(. 1) storage structure: Hashtable hash table storage structure
(2) and disadvantages:
Advantages: fast addition rate query speed, speed deleted
disadvantages: disordered

TreeSet
(. 1) storage structure: binary tree storage structure
(2) and disadvantages:
Advantages: ordered (sorted in ascending order) is faster than List query
(query by content)
disadvantages: Query speed is not fast HashSet


17. Using HashSet to store custom objects, why the need to rewrite hashCode () and equals ()?


HashSet hash table structure storing a hash table, need to use the hashCode () and equals () method:
hashCode () generated hash value to calculate a memory location;
when the hash values are the same for a call equals () methods were compared.
If you do not override, the call is the Object of hashcode, and the Object hashCode actually address. The system has covered class hashCode method.
So HashSet storage of custom objects to override the hashCode () and equals () method, the purpose is to tell the program to remove duplicate elements of the strategy.


18. Using TreeSet store multiple student data to achieve sorted by different attributes values?


(1) Create a Student class implement Comparable interface;
publicclass Student implementsComparable {
// private attributes;
privateint ID;
privateint Score;
// getters and setter methods;
publicint getScore () {
return Score;
}

publicvoid setScore(int score) {
this.score = score;
}

publicint getId() {
return id;
}

the setId publicvoid (int ID) {
this.id ID =;
}
// constructor;
public Student () {

}

public Student(int id, int score) {
super();
this.id = id;
this.score = score;
}

@Override
public String toString() {
return"Person [id=" + id + ", score=" + score + "]";
}
//实现compareTo方法,这里是用id比较;
publicint compareTo(Object obj){
Student other=(Student)obj;
int result=this.id-other.id;
return result;
}

}

(2) was added TreeSet;
publicclass Test2 {
publicstaticvoid main (String [] args) {
/ *
There are two ways to create a time reference to the following TreeSet:
Code 1: Using the constructor with no arguments TreeSet (), when added to it Student object, ordering comparison with the policy when the internal student implemented
compareTo method (internal comparator, id sorting according to this example, students).
Code 2: There are parameters using the constructor new TreeSet (scoreComp); so what parameters scoreComp is it? It is represented by an external comparator to the
object. Under what circumstances do? When implemented with sorting TreeSet, we do not want to use Student's internal comparator (that is to say do not want to sort by id),
I want to sort by students score? then what should we do? Some students say the chant internal comparator change it, change the ranking with a score. But change to change is not enough
flexibility to do? We have another way. Remember external comparator it? Student's internal comparator and we will not change, and then define one of the Student class
external comparators (see section following code "is defined external comparator"), the definition of external comparator to implement Comparator interface Compare
(Object OBJ1, Object obj2) (if you forget to forward looking through it), implemented by the score (score) compare in this method.
So, if you want to compare with other attributes (such as age, name, etc.), may continue to define the corresponding external comparator, so that
the method 2. Referring codes
* /


/ *
Code. 1:
the Set new new TreeSet TreeSet = ();
* /

/ *
Code 2:
ScoreComp scoreComp new new ScoreComp = (); // define an external comparator object;
the Set new new TreeSet TreeSet = (scoreComp); // the external object as a parameter comparator constructor TreeSet;
* /
Student P1 Student new new = (1,78);
Student Student new new P2 = (2,67);
Student Student new new P3 = (3,96);
Student Student new new P4 = (4,87);

treeSet.add (P3);
TreeSet .add (P4);
treeSet.add (P1);
treeSet.add (P2);

the Iterator treeSet.iterator IT = ();

the while (it.hasNext ()) {
System.out.println (it.next ()) ;
}

}

}

// define external comparator;
class ScoreComp implementsComparator {

publicint Compare (OBJ1 Object, Object obj2) {

Student P1 = (Student) OBJ1;
Student P2 = (Student) obj2;
int Result = p1.getScore () - p2.getScore ( ); // Sort by scores of students;
return the Result;

}

}


19. [machine] Description Comparable interface role. And define a student class, to compare the size of the use of scores.


Custom class, though not as the same kind of thing, but the right to have comparable Student, Product, Person, etc., can achieve comparable functionality. Since it
is the same function (comparison), it will define an interface, the method defined in the interface where to go by each class implementation.
Comparable interface implemented compareTo method need to achieve, can be sorted according to specific objects in the container based on the collation method.
Student implementsComparable {publicclass
privateintid;
Private String Sex;
Private String name;
privateint Score;
privateintage;

public Student () {
}
public Student (int ID, Sex String, String name, int Score, int Age) {
this.id ID =;
Sex = this.sex;
this.name = name;
this.score = Score;
this.age = Age;
}
publicint the compareTo (Object O) {
Student S = (Student) O;
returnthis.score-s.score;
}
}

 

In 20.Map, key can be repeated? If you repeat, what phenomenon?


key: random, unique;
add duplicate key is not being given, we will repeat until the key cover.


Map and similar 21.Set collection class name, there is no correlation?


These collections HashMap and HashSet uses a hash table structure, and the need to use a hash code equals hashCode method.


[22] on the integrated use of machine List, Map container storage as data, and remove the "John Doe" from the map.


Name: Joe Smith Age: 18 Weight: 90 Address: Beijing
Name: John Doe Age: 28 Weight: 50 Address: Shanghai
Note: You can not use Javabean package!

(1)先创建Person类;
publicclass Person {
//私有属性;
private String name;
privateint age;
privatedouble weight;
private String address;

//getter和setter方法(略);
//构造方法;
public Person(String name, int age, double weight, String address) {
super();
this.name = name;
this.age = age;
this.weight = weight;
this.address = address;
}

@Override
public String toString() {
return"Person [name=" + name + ", age=" + age + ", weight=" + weight + ", address=" +
address + "]";
}
}
(2)用List存放数据:
List<Person> personList=new ArrayList<Person>();

Person p1 = new Person ( "Joe Smith" 18.90, "Beijing");
Person P2 = new new Person ( "John Doe", 28, 60, "Shanghai");

// Add the Person object to personList Lane;
personList.add (P1);
personList.add (P2);

(3) Map Data storage:
Map <String, Person> = new new map the HashMap <String, Person> ();
// add to the Person object in the map, as with the Key name, as the Person object value;
map.put ( p1.getName (), P1);
map.put (p2.getName (), P2);
// extract the name "John Doe" person's information, using as map.get (key) method returns this key value corresponding to a value;
System.out.println (as map.get ( "John Doe"));

 

[23] use JavaBean packaging machine, a subject completed the exercise.


[24] machine to write generic examples List, Set, Map used.


ArrayList <String> aList = new ArrayList <String> (); // can only receive an object of type String;
the Set <Integer> = new new SET HashSet <Integer> (); // can only receive an object of type Integer;
the Map < Integer, String> map = new Map <Integer, String> (); // can receive key type Integer, value type is String.


25. What are the benefits using generics?


Generic JavaSE1.5 is a new feature, the nature of the parameter of the generic type, the type of data that is being operated is specified as a parameter. Java language to introduce
the benefits of generics is safe and simple.


[26] machine with three ways to traverse the code written in List


finalintSIZE = list.size();
for (int i = 0; i <SIZE; i++) {
String s = list.get(i);
System.out.print(s+"");
}
System.out.println();
for (String string : list) {
System.out.print(string+"");
}
System.out.println();
Iterator<String> it = list.iterator();
while(it.hasNext()){
String s = it.next();
System.out.print(s+"");
}
}

 

[27] machine with two ways to write the code to traverse the Set


1)增强for循环遍历
for (Integer integer : set) {
System.out.print(integer.intValue() + "");
}
2)Iterator 遍历
Iterator<Integer> iterator = set.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next().intValue() + "");
}

 

[28] machine code writes a manner to traverse the map


1:得到所有的key
Set<String> set = map.keySet();
Iterator<String> iterator = set.iterator();
while(iterator.hasNext()){
String key = iterator.next();
System.out.println(key + "--->"+map.get(key));
}
2:得到所有的value
Collection<String> collection = map.values();
for (String string : collection) {
System.out.println("value--->"+string);
}
3:得到所有的key和value
Set<Entry<String, String>> entries = map.entrySet();
Iterator<Entry<String, String>>iterator2 = entries.iterator();
while (iterator2.hasNext()) {
Entry<String, String> entry = iterator2.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "--->"+value);
}

 

29. The use of enhanced for loop iterates List or Set, List or Set if not added generics, can traverse it?


can.


30. If I want to remove elements while traversing, which traversal using the best?


Iterator interface. There are ways to remove Iterator remove elements.

 

31.Iterator is an interface or class?


Iterator interface.


32.Collection and Collections What is the difference?


Collection is a set of Java provides an interface, a storage group is not unique, unordered objects. It has two sub-interfaces List and Set.
There is also a Java Collections classes, designed to operate collections, it offers a range of static methods to achieve a variety of search collection, sorting, threading
the safety of the operation.

 

33. What is the role of the resource file?


Resource files are used for configuration information, such as database information, key information and so on. Program in the need to have a way to read configuration information resource file. As
if there is no resource file, you have to write the configuration information in the code; you have to modify the code if necessary modify the information. With the resource file after, once the information needs
change, you can modify the resource file, without modifying the code, the better to ensure that the packaging of the code.

 

34. [machine] to create a resource file (does not include the Chinese) in src, try to use the Property in class reading

Property surface.


(1) create a resource file, I was fruit.properties; "fruit" can be customized, the suffix is "properties". I write the contents of the file are as follows
(fruit fruits name corresponding information: name, origin, price):
the Apple = name: the Apple, Place: ShanDong,. Price: 7.00RMB / 500 g
Orange = name: Orange, Place: Agriculture & Animal,. Price: 3.99 RMB / 500 g of
Banana = name: Banana, Place: Hainan,. price: 2.99RMB / 500 g of
Carrot = name: Carrot, Place: Beijing,. price: 2.98RMB / 500 g of
(2) code portions:
publicclass TestProperties {

main publicstaticvoid (String [] args) throws IOException {

File File = new new File ( "fruit.properties"); // file path parameters;
the InputStream new new IS = the FileInputStream (File); // build the file input stream;
the Properties p = new Properties (); // create a resource file objects;
p.load (iS); // load the resource files

String fruitInfo = p.getProperty ( "orange" ); // getProperty () parameter is the resource file key value,
enter "Apple", "Orange", "Banana", "Carrot."
System.out.println (fruitInfo); // fruitInfo fruit information obtained by the input key value.

}
}

 

[35.] Use machine entrySet Traversing Map.


Set<Entry<String, String>> entries = map.entrySet();
Iterator<Entry<String, String>>iterator2 = entries.iterator();
while (iterator2.hasNext()) {
Entry<String, String> entry = iterator2.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + "--->"+value);
}


ArrayList difference 36.Vector and links


Vector and ArrayList and contact distinction
achieve the same principles, the same functions, variable-length array of structures are, in many cases used interchangeably
main differences are as follows
. 1) Vector early JDK interfaces, new ArrayList alternative interfaces Vector
2) Vector thread-safe, ArrayList speed of light heavy security, non-thread-safe
3) the length of time required to grow, Vector default doubled, ArrayList increase of 50%

 

HashMap difference 37.Hashtable and links


Achieve the same principles, the same functions, the underlying structure is a hash table, query speed, in many cases used interchangeably
main differences are as follows
1) Hashtable is an interface provided by the JDK earlier, the HashMap is a new version of the interface provided by the JDK
2 ) Hashtable class inherits Dictionary, HashMap implements the Map interface
3) Hashtable thread-safe, HashMap non-thread-safe
4) Hashtable does not allow null values, HashMap allows null values

 

Select according to major container 38.Java and applications


(1) HashTable, Vector class are synchronized, and HashMap, ArrayList not synchronized. So when in the case of multi-threaded, you should use
HashTable and Vector, the opposite should use HashMap, ArrayList.
(2) In addition to the time required to sort use TreeSet, TreeMap, but should be used HashSet, HashMap, because of their higher efficiency.
(3) ArrayList constructed from an array, LinkList build a doubly linked list, so the program should always add, delete elements when the speed to be faster, better use
LinkList, while in other cases the best use ArrayList. Because he provides faster random access elements.

Guess you like

Origin www.cnblogs.com/ren549047861/p/11294102.html