我正在研究hashtable。我想在其中形成哈希表但我的外部哈希表的值被替换。
Hashtable1 [键,哈希表[键,值]]
我能够获得outerhashtable密钥而不会覆盖,但内部散列表值会被替换。
import java.io.*;
import java.util.*;
import com.sridhar.util.*;
public class MyTokenizerDemo
{
public static void main(String[] args) throws IOException
{
Hashtable ht=new Hashtable();
Hashtable ht1=new Hashtable();
Hashtable ht2=new Hashtable();
File f = new File("E:/rum/format.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
ArrayList aList = (ArrayList)StringUtils.myTokenizer(s,"~!~");
for(int i=0;i<aList.size();i++)
{
ArrayList aList1 = (ArrayList)StringUtils.myTokenizer((String)aList.get(i),"$#$");
//System.out.println("==>"+aList1.get(0)+"<==");
ArrayList aList2 = (ArrayList)StringUtils.myTokenizer((String)aList1.get(1),"~$~");
//System.out.println("====>"+aList2+"<=====");
for(int j=0;j<aList2.size();j++)
{
ArrayList as = (ArrayList)StringUtils.MyTokenizer((String)aList2.get(j),"#$#");
if(as!=null)
{
String innerkey = (String)as.get(0);
String innervalue = (String)as.get(1);
ht2.put(innerkey,innervalue);
}
}
ht1.put(aList1.get(0),ht2);
}
}
System.out.println(ht1);
}
}
请在我自己的字符串标记实用程序类中进行假设。
我的外部Hashtable值被覆盖。
在这个问题上帮助我。
答案 0 :(得分:0)
将此代码ht1.put(aList1.get(0),ht2);
修改为ht1.put(aList1.get(i),ht2);
当您调用asList1.get(0)时,始终键将相同,因此您的数据将被覆盖
答案 1 :(得分:0)
我在这里犯了一个简单的错误!! for循环中的实例化使值保持活着而不是覆盖!!谢谢大家!!下面是代码!
import java.io.*;
import java.util.*;
import com.sridhar.util.*;
public class MyTokenizerDemo
{
public static void main(String[] args) throws IOException
{
Hashtable ht=new Hashtable();
Hashtable ht1=new Hashtable();
Hashtable ht2=new Hashtable();
File f = new File("E:/rum/format.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s;
while((s=br.readLine())!=null)
{
ArrayList aList = (ArrayList)StringUtils.myTokenizer(s,"~!~");
for(int i=0;i<aList.size();i++)
{
ht2 = new Hashtable(); //Instantiating inside the loop makes to work perfect :)
ArrayList aList1 = (ArrayList)StringUtils.myTokenizer((String)aList.get(i),"$#$");
//System.out.println("==>"+aList1.get(0)+"<==");
ArrayList aList2 = (ArrayList)StringUtils.myTokenizer((String)aList1.get(1),"~$~");
//System.out.println("====>"+aList2+"<=====");
for(int j=0;j<aList2.size();j++)
{
ArrayList as = (ArrayList)StringUtils.MyTokenizer((String)aList2.get(j),"#$#");
if(as!=null)
{
String innerkey = (String)as.get(0);
String innervalue = (String)as.get(1);
ht2.put(innerkey,innervalue);
}
}
ht1.put(aList1.get(0),ht2);
}
}
System.out.println(ht1);
}