将名称存储在向量中并将数据转换为Java中的哈希表

时间:2012-03-05 05:44:20

标签: java hashtable

我需要将一些名称存储到一个向量中,然后将该数据转换为哈希表。哈希表条目的id将是序列号。我做的是

import java.io.*;
import java.util.*;

class VecToHash{
public static void main(String [] args){
Vector<String> vec = new Vector<String>(); 

Hashtable names=new Hashtable();
vec.addElement(new String("name1"));
vec.addElement(new String("name2"));
vec.addElement(new String("name3"));
vec.addElement(new String("name4"));
vec.addElement(new String("name5"));

int VecSize=vec.size();

for (int i=0;i<VecSize;i++){
for (int j=0;j<VecSize;j++){
names.put(("j"), new String(vec.elementAt(i)));
    }

Set set=names.keySet();
Iterator itr=set.iterator();

while (itr.hasNext()){
String str=(String) itr.next();
System.out.println(str+":"+names.get(str));}
System.out.println();
}}}

但它没有将序列号作为ID,我也需要删除Hastable中的重复项。请帮帮我。

2 个答案:

答案 0 :(得分:2)

噢,HashtableVector,非常老派。我想知道你是否可以使用SetHashMap简化事情?

类似的东西:

Set<String> vec = new HashSet<String>(); 

Map<Integer, String> names = new HashMap<Integer, String>();

//the set will automatically filter out duplicate values
vec.add(new String("name1"));
vec.add(new String("name2"));
vec.add(new String("name3"));
vec.add(new String("name4"));
vec.add(new String("name5"));

Integer serialNumber = 0;
for (String name : vec) {
    names.put(serialNumber, name);
    serialNumber++;
}

for (Integer temp : names.keySet()) {
    System.out.println(temp + ":" + names.get(temp));
    System.out.println();
}

答案 1 :(得分:0)

这是正确的代码。

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Vector;


public class Main {
/**
 * @param args
 */
/*public static void main(String[] args) {
    List<Integer> intList = new ArrayList<Integer>();
    intList.add(0, new Integer(1));
    intList.add(1, new Integer(1));
    intList.add(2, new Integer(1));
    intList.add(3, new Integer(1));
    intList.add(4, new Integer(1));
    intList.add(5, new Integer(1));

}*/


public static void main(String [] args){
Vector<String> vec = new Vector<String>(); 

Hashtable<Integer, String> names=new Hashtable();
vec.addElement(new String("name1"));
vec.addElement(new String("name2"));
vec.addElement(new String("name3"));
vec.addElement(new String("name4"));
vec.addElement(new String("name5"));

int VecSize=vec.size();

for (int i=0;i<VecSize;i++){

names.put(new Integer(i), new String(vec.elementAt(i)));
}

Set set=names.keySet();
Iterator itr= set.iterator();

while (itr.hasNext()){
Integer temp = (Integer) itr.next();
System.out.println(temp+":"+names.get(temp));}
System.out.println();
}}