I want to add a String to a list, but I get the error
Type mismatch: cannot convert from String to List

Initially I did it as follows:

List accDetails = tm.get(accNo);

and then like this:

String conv = (String)tm.get(accNo);
List accDetails = conv;

Both have the same problem.

note: tm is a TreeMap

What am I doing wrong?

Create an instance of List to add an element,

TreeMap<String,String> map=new TreeMap<String,String>();
      map.put("foo","foobar");
   
      List<String> list=new ArrayList<String>();   
      list.add(map.get("foo"));

That would work, yes.

I realize that I forgot to fully explain my problem, though.

When I do the following:

List accDetails = tm.get(accNo);

...accNo is a variable that is set shortly prior to the above piece of code. It might not yet be in the TreeMap. I will put all the code here. Sorry for the misunderstanding.

public static void main(String[] args) {
		//String dir = args[0].toString();
		TreeMap tm = new TreeMap(); 
		
		try {
			FileInputStream fiStream = new  FileInputStream("C:\\Work\\Tracker\\TEST.txt");
			DataInputStream diStream = new DataInputStream(fiStream);
			BufferedReader bReader = new BufferedReader(new InputStreamReader(diStream));
			String inLine;
			
			while ((inLine = bReader.readLine()) != null) {
				// Row gets inserted into the Treemap as the key, with the account number as the value 
				String [] record = inLine.split("\\|", -1); // Splits the record, keeps empty fields.
				
				String accNo = record[0];
				String restOfLine = "";
				List list = new ArrayList();
				
				for (int i = 1; i < record.length; i++) {
					restOfLine = restOfLine + "," + record[i];
				}
				
				if (!record[0].equals("ACCOUNT NUMBER")) {
				tm.put(accNo, restOfLine);
				}
				//type mismatch: cannot convert from Object to List
				String conv = (String)tm.get(accNo);
				List accDetails = tm.get(accNo);
				if (conv == null) {
					accDetails = new ArrayList()
				}
				accDetails.add(restOfLine);
				
				tm.put(accNo, accDetails);
			}
			bReader.close();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.