I have managed to fetch a string from the database and be able to store some of its elements in variable so as to reduce the number of times the app interacts with the databse. However I wanted the first element to be fetched from the database to be stored in a list but it keeps generating an error when i parse the string to a new list. please help
//String fetched from the database
final String[] rec = split(myresult,seperator);
//loc is the first String to be parsed to a String..
//desc is the 2nd string to be parsed to a textarea
//coords 3rd string which contains coordinates..
String loc=rec[0];
final String desc=rec[1];
String coords=rec[2];
//ERROR IS GENERATED HERE!!!
listmboya=new List(loc);
//Separate the coordinates in the string...
String seperator2=",";
String [] coordinates=split(coords,seperator2);
String lat=coordinates[0];
String lot=coordinates[1];
//convert them to floats..
item1=Float.parseFloat(lat);
item2=Float.parseFloat(lot);
list is an iterface,
try
listmboya=new ArrayList();
listmboya.add(loc);
You cannot instantiate List object. Its an interface and not a class. You need an ArrayList which is the implementing class of List and also, there is no constructor for ArrayList that takes String as parameter.
So, you need to create an ArrayList<String> and then add your String to it.
So you need to do it like this: -
List<String> listmboya=new ArrayList<String>();
listmboya.add(loc);
Make sure to declare your listmboya as List<String>
UPDATE: - Post some more Code in case this doesn't work. We need to look at more of them.
List is the abstract class, can not be instantiated.
just try like this:
listmboya = new ArrayList<String>();
listmboya.add(loc);
Related
I am creating an inverted index dictionary, which takes a million or so tweets from a file, stores the words from these tweets as the Keys in the dictionary (HashMap) and a pointer to a postings list (LinkedList) which contains the document ID (tweet username, date etc.) as the Value of the key.
My function stores the words as the key for the HashMap with no problem and should store an object pointer to the postings list for each occurrence of the word as the value for the key. But for some reason when I try to update the list it doesn't work. Once the entire file has been read through, the HashMap contains the keys with null Objects as their values.
The code here:
String line = scanner.nextLine();
String[] lineArr = line.split(" ");
DocID id = new DocID(lineArr[0], lineArr[1],lineArr[2]);
for(int i=3; i<lineArr.length; i++){
ListPointer list = new ListPointer();
if(dict.containsKey(lineArr[i].toLowerCase())) list = dict.get(lineArr[i]);
list.postings.add(id);
dict.put(lineArr[i].toLowerCase(), list);
}
}
should store an Object with a list attribute as the value, effectively acting as a pointer to a list. If a similar key exists in the table, the value is obtained and the list attribute of that value should be updated and set again as the value for that key.
I know using a LinkedList as the value of the HashMap rather than using an object containing an inherent list would be better, but we were instructed that the postings list should be stored separately and shouldn't be an attribute of the dictionary class, and the dictionary should just contain a pointer to its relevant postings list.
So far these are the objects with their members:
public static HashMap<String, ListPointer> dict;
public static class DocID{
public String userID;
public String date;
public String time;
public DocID(String dte, String tme, String id){
this.userID = id;
this.date = dte;
this.time = tme;
}
}
public static class ListPointer{
public static LinkedList<DocID> postings;
public ListPointer(){
postings = new LinkedList<DocID>();
}
}
I could understand if it was an overwriting error, but no, the value of each key in the HashMap upon complete read through of the file is null and I have no idea why this could be?
Your postings member shouldn't be static. You have a single instance shared across all ListPointer instances, and you overwrite it with an empty LinkedList<DocID> each time the ListPointer constructor is invoked.
Change
public static LinkedList<DocID> postings;
to
public LinkedList<DocID> postings;
EDIT :
You have another problem in the retrieval from the Map :
Change
if(dict.containsKey(lineArr[i].toLowerCase())) list = dict.get(lineArr[i]);
to
if(dict.containsKey(lineArr[i].toLowerCase())) list = dict.get(lineArr[i].toLowerCase());
If you are passing a lower case String to containsKey, you must pass the same lower case String to get. Otherwise get will return null if the original key wasn't lower case.
I see two issues:
Issue 1.
public static class ListPointer{
public static LinkedList<DocID> postings;
...
The class ListPointer does not need to be static and the member "postings" does not to be static either.
Issue 2
if(dict.containsKey(lineArr[i].toLowerCase())) list = dict.get(lineArr[i]);
I think the main problem is in this line. you are trying to match everything in lower case, but when you get the key from dict you aren't using .toLowerCase()
I am currently scraping data from a HTML table using JSoup then storing this into an ArrayList. I would then like to store these values within a SQL database. From what I understand these must be converted to a String before they can be inserted into a database. How would I go about converting these ArrayLists to a String?
Here is my current code:
Document doc = Jsoup.connect(URL).timeout(5000).get();
for (Element table : doc.select("table:first-of-type"))
{
for (Element row : table.select("tr:gt(0)")) {
Elements tds = row.select("td");
List1.add(tds.get(0).text());
List2.add(tds.get(1).text());
List3.add(tds.get(2).text());
}
}
To get all the values you need, you can iterate through the list very easily :
public static void main(String[] args) {
List<String> List1 = new ArrayList<>();
for (String singleString : List1){
//Do whatever you want with each string stored in this list
}
}
Well i am not really sure if there is some special way to achieve what you are asking .
You would need to iterate over the array . You could use the StringBuilder instead of String for a bit of optimization. I am not really sure how much of a boost you would gain in performance ..
Anyway this is how the code would look ..
StringBuilder sb = new StringBuilder();
for (Object o : list1){
sb.append(o.toString()+delimiter); // delimiter could be , or \t or ||
//You could manipulate the string here as required..
// enter code here`
}
return sb.toString();
You would then need to split the strings if required. ( if they need to go into seperate fields
Java collection framework doesn't provide any direct utility method to convert ArrayList to String in Java. But Spring framework which is famous for dependency Injection and its IOC container also provides API with common utilities like method to convert Collection to String in Java. You can convert ArrayList to String using Spring Framework's StringUtils class. StringUtils class provide three methods to convert any collection
e.g. ArrayList to String in Java, as shown below:
public static String collectionToCommaDelimitedString(Collection coll)
public static String collectionToDelimitedString(Collection coll, String delim)
public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix)
got it....
I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );
I have a list of URL's added to a String[] with this.
try {
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
for(String thumb : thumbLinks) {
System.out.println(thumbLinks.get(1));
}
}
How can i add each String that is loaded into a separate String?
EDIT:
SO as the images are loaded into the thumbLinks list. I want to get each link to a seperate
String url1;
String url2;
String url3;
If you expect a fixed number of items, and you have a fixed number of String variables, you have little choice but something like:
String url0 = thumbLinks.get(0);
String url1 = thumbLinks.get(1);
...
String url5 = thumbLinks.get(5);
Well, you could do something grim with reflection, I guess. But probably best to avoid this at all.
take a String array of the size of your ArrayList object - thumbLinks in your case. take an int variable and initialize it with zero. I have made some changes in your code just have a look:
try{
Elements thumbs = jsDoc.select("div.latest-media-images img.latestMediaThumb");
List<String> thumbLinks = new ArrayList<String>();
for(Element thumb : thumbs) {
thumbLinks.add(thumb.attr("src"));
}
String[] urls = new String[thumbLinks.size()];
int x =0;
for(String thumb : thumbLinks) {
urls[x++] = thumb;
}
}catch(Excpetion e){
}
use urls for your purpose
ArrayList has method public <T> T[] toArray(T[] a) that you can call as described below on thumbLinks:
String[] url = new String[thumbLinks.size()];
url = thumbLinks.toArray(url);
Then, you will have an array of strings that you can access like this:
System.out.println(url[0]);
System.out.println(url[1]);
System.out.println(url[2]);
// etc, etc. all the say up to thumbLinks.size() - 1
While this is not exactly what you've asked for, it's pretty much the same thing. If you really want variables named url1, url2, url3, etc., you're likely going to have to code it line by line for every element in the list.
Just as an aside, you don't need an array to access the elements of your thumbLinks list directly. You can already do this:
System.out.println(thumbLinks.get(0));
System.out.println(thumbLinks.get(1));
System.out.println(thumbLinks.get(2));
// etc. all the way up to thumbLinks.size() - 1
How can I fix this:
class Name {
public void createArray(String name)
{
String name=new String[200];//we know, we can't do this- duplicate local variable,need a fix here.
}
}
I want to create array of strings with name of array as input parameter = name,
Example:
1) for function call createArray(domain1) -> I need essentially this to happen-> String domain1=new String[200];
2)for function call createArray(domain22)-> I need function to create String domain22=new String[200];
Hope this edit helps.
NOTE: There is a possibility that same name is passed byfunction twice/thrice. like createArray(domain1);, at that point of time I want to ignore the creation of array.
Store your new String[200] objects in a Map keyed by the name
Map<String, String[]> myarrays = new HashMap<String, String[]>();
myarrays.put("name", createArray("name"));
myarrays.put("test", createAray("test"));
then when you want one of them do
String[] data = myarrays.get("test");