Some common Java and Android interview questions

2016.10.06

    The difference between Vector and ArrayList

    Both Vector and ArrayList are implementation classes of the List interface, and they both represent data structures in the form of linked lists.

    The use of the two is similar. Generally, elements are added by the add() method; elements are removed by the remove() method, and size() is used to obtain the number of set elements.

import java.util.ArrayList;
import java.util.Vector;

public class ListText {

	public static void main(String[] args) {
         Vector<String> v = new Vector<String>();//Create a Vector object
         v.add("hello");//Add elements
         v.remove("hello");//Remove element
         System.out.println(v.size());//Get the number of elements of the vector
         ArrayList<String> al = new ArrayList<String>();//Create an ArrayList object
         al.add("hello");//Add elements
         al.remove("hello");//Remove element
         System.out.println(al.size());//Get the number of elements in the linked list object
	}
}

    The output is:

    0

    0

    Answer: Vector is thread-safe because its methods of manipulating elements are synchronized, while ArrayList is not. In the development process, you should choose according to your needs. If you want to ensure thread safety, you need to use Vector, and when it is not necessary, you don't need to use Vector, because ArrayList will be more efficient.

 

    Difference between HashMap and HashTable

    For the Map interface, it has two important implementation classes HashMap and HashTable. When they store elements, they are all out of order, but there are certain differences.

import java.util.HashMap;
import java.util.Map;

public class MapText {
       public static void main(String[] args){
    	   
    	   Map<String,String> map= new HashMap<String,String>();//Create a Map object
    	   map.put("a", "123");//Store the element
    	   map.put("b", "456");
    	   map.put("c", "789");
    	   for(String key:map.keySet()){//traverse through the set of keys
    		   System.out.println(key+":"+map.get(key));//Use the get method to get the value
    	   }
       }
}

    The main differences between HashMap and HashTable are as follows.

    1. The method of HashTable is synchronous, but HashMap cannot be synchronous.

    2. HashTable does not allow null values ​​(neither key nor value), HashMap allows null values ​​(both key and value).

    3.HashTable has a contains() method, which has the same function as Contains Value().

    4. HashTable uses Enumeration, HashMap uses Iterator.

    5. The initial size of the hash array in the hashTable and its growth method are different.

    6. The use of hash values ​​is different. HashTable directly uses the hashCode of the object, while HashMap will recalculate the hash value.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326941996&siteId=291194637