The line I get an error on is this:

List accDetails = (List)tm.get(accNo)

"tm" is a TreeMap, and "accNo" is a value in it.
accNo is a String. I get a build error like this:

java.lang.String cannot be cast to java.util.List

I have no idea what to do here, I've tried by myself, and I've googled myself silly, but still no answer...

Can anyone here help?

7 Years
Discussion Span
Last Post by P00dle

Seems as though it is Strings stored in the map and that the map was declared using generics.

So, why are you trying to use a String as a List?

IOW, what is in the map and what are you trying to do here?

Edited by masijade: n/a


the entire piece of code looks like this:

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 = "";
				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
				List accDetails = (List)tm.get(accNo);
				if (accDetails == null) {
					accDetails = new ArrayList();
				tm.put(accNo, accDetails);

so basically, the map holds account numbers and the details associated with them.

I declare that list and assign it a value, and immedialty afterwards I check if it's null or not.

I just want to know how I can get that String into that List


Well, what is stored in the Map is a String, you cannot simply cast a String to a List. Do you want to create a List from multiple elements in this String, or do you want to simply add this String (and other's like it) to another list? If the second, you, of course, want to use add. If the first, the use split (if applicable) and create an array, instead.



Solved my problem, and gave me a better idea as well :P

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.