ArrayList strange behaviour [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can anybody tell me what's wrong with my code
latest_songs,top_songs and hit_songs are arraylist.song() is a static method in Parseurl where i fetch the json array.it working fine & return proper data.
latest_Songs = ParseUrl.song(url1);
Log.i("ring,latest=", latest_Songs.toString());
top_Songs = ParseUrl.song(url2);
Log.i("ring,top=", top_Songs.toString());
hit_Songs = ParseUrl.song(url3);
Log.i("ring,hits=", hit_Songs.toString());
it works fine when i run latest_songs and top_songs.problem is with hit_songs.as i write this in my project both arraylist(latest_songs and top_songs) data overrided with hits_songs.where i am doing wrong.
this is ParseUrl from where i retrieve data in each arraylist
public class ParseUrl {
static ArrayList<String> songs_List = new ArrayList<String>();
static ArrayList<String> songs_Names = new ArrayList<String>();
static ArrayList<String> songs_Urls = new ArrayList<String>();
static File tempFiles;
File ringtones;
public static ArrayList<String> song(String url) {
songs_Names.clear();
songs_Urls.clear();
JSONObject json = JsonParse.getSongfromUrl(url);
try {
JSONArray latestSongs = json.getJSONArray("ringtones");
for (int count = 0; count < latestSongs.length(); count++) {
JSONObject song = latestSongs.getJSONObject(count);
songs_List.add(song.toString());
JSONArray name = song.names();
songs_Names.add(name.toString());
String songUrl = name.toString();
String URL = songUrl.substring(2, songUrl.lastIndexOf("\""));
songs_Urls.add(song.getString(URL));
}
} catch (JSONException e) {
e.printStackTrace();
}
return songs_Names;
}

Your arraylist is a static variable inside your class.So there is only one arraylist in memory.Each time you call the song method , you are modifying the same list.That means your latest_songs,top_songs,hit_songs, all will be pointing to same list.That is the reason your list is getting over ridden.
Try creating a list inside your method and return it rather than going for static variables.

Are you changing the url value anywhere?
Because you are assigning ParseUrl.song(url) to all the three array lists. Unless url is changed somewhere, all three array lists will have the same value since ParseUrl.song(url) will give the same result.

Related

ArrayList return empty value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have one problem in code regarding Arraylist. I have two methods one method works with server to get data and inside this method i'm adding data to ArrayList. Second method is getter that will return Arraylist. But when I display data with using Log.d() inside first method ArrayList has data. But when i try call second method ArrayList is empty. Help me!!! Thank you in advance!!!
Below shows piece of code first method that will fetch data from server
try {
JSONArray jsonArray= new JSONArray(response);
for(int i=0; i<jsonArray.length(); ++i)
{
ordersLists.setId(jsonArray.getJSONObject(i).getString("id"));
ordersLists.setMain_cat(jsonArray.getJSONObject(i).getString("main_cat"));
ordersLists.setSub_cat(jsonArray.getJSONObject(i).getString("sub_cat"));
ordersLists.setDate(jsonArray.getJSONObject(i).getString("date"));
ordersLists.setPrice(jsonArray.getJSONObject(i).getInt("price"));
ordersLists.setComment(jsonArray.getJSONObject(i).getString("comment"));
ordersLists.setCity(jsonArray.getJSONObject(i).getInt("city"));
arrayList.add(ordersLists);
}
Second method is getter.
public ArrayList<OrdersLists> getArrayList()
{
return arrayList;
}
From what I understood from your question , I think the solution is to replace this line if your first method from
arrayList.add(ordersLists);
to
the name of your object that has the arrayList .setArrayList(ordersLists);
where the setter method setArrayList in this form below :
public void setArrayList(ArrayList<String> arrayList)
{
this.arrayList= arrayList;
}
https://www.codejava.net/coding/java-getter-and-setter-tutorial-from-basics-to-best-practices
Let me know if that helped!
In your code, you initialize i = 0 then try to make a decrement.
But I think that you can't have an index below zero.
for(int i = 0; i < jsonArray.length(); ++i) {
}
Try this instead:
for(int i = 0; i < jsonArray.length(); i++){
}
try this
JSONArray jsonArray= new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++)
{
ordersLists = new OrdersLists();
ordersLists.setId(jsonArray.getJSONObject(i).getString("id"));
ordersLists.setMain_cat(jsonArray.getJSONObject(i).getString("main_cat"));
ordersLists.setSub_cat(jsonArray.getJSONObject(i).getString("sub_cat"));
ordersLists.setDate(jsonArray.getJSONObject(i).getString("date"));
ordersLists.setPrice(jsonArray.getJSONObject(i).getInt("price"));
ordersLists.setComment(jsonArray.getJSONObject(i).getString("comment"));
ordersLists.setCity(jsonArray.getJSONObject(i).getInt("city"));
arrayList.add(ordersLists);
}

Java 8 Stream | Add a value of the stream to another List/Collection without using foreach or any terminal Operation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So far i tried to add values from a stream to a list with peek() but later I found out that peek() is only used "to support debugging, where you want to see the elements as they flow past a certain point in a pipeline".
Now my question is whats the coding-convention here ?
Do I map it in a second stream or can I map it one String like my Code with Peek() ?
final int range = 9;
List <String> help = new ArrayList<String>();
//random numbers to fill help
for(int i = 5;i< range;i++)
{
help.add(String.valueOf(i+(i*2)+(i*(i+2))) );
}
List<Test> others = new LinkedList<>();
List<Test> tests = help.stream().map(s-> new Test(s,(int) Integer.valueOf("10")))
.peek(t->System.out.println(t.getText()))
.peek(t-> others.add(t)).collect(Collectors.toList());
The class Test looks like this:
public class Test
{
String text;
int id;
public Test(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public int getId() {
return id;
}
}
You could add that functionality to the lambda in the mapping part:
List<Test> tests = help.stream().map(
s-> {
Test t = new Test(s,(int) Integer.valueOf("10")));
System.out.println(t.getText());
others.add(t)
return t;
}
.collect(Collectors.toList());
That simply moves your extra steps into an existing step, avoiding any further loops etc

Change method return type to List<String> java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In my application I have a method fetchJSONChild() as below:
public List<String[]> fetchJSONChild(){
final List<String> child;// = new ArrayList<String>();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
String data1 = "1,2,3";
//String[] parts = new String[3];
child = new ArrayList<String>(Arrays.asList(data1.split(",")));
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
return child;
}
In this method I have created a list and put splitted string items on it but when I return this list, I am getting an error at this line return child; as below:
Change method return type to List<String>
How can I resolve it?
Thanks
As mentioned by others you have to change List<String[]> to List<String>. You can't assign a new ArrayList to child because you declared it to be final. Besides that your code is really messed up and your Thread makes no sense. You should instead do something like this:
// Don't use a thread in your method.
public List<String> fetchJSONChild(){
final String data1 = "1,2,3";
final List<String> child = new ArrayList<String>(Arrays.asList(data1.split(",")));
return child;
}
// Call your method in a thread elsewhere
new Thread(new Runnable() {
#Override
public void run() {
// Since the method is not static, you need a reference to an object which declares this method.
final List<String> chils = yourObject.fetchJSONChild();
// Do something with your list
}
}).start();
Change:
public List<String[]> fetchJSONChild(){
to:
public List<String> fetchJSONChild(){
You're trying to return an ArrayList<String> but the return type of your method is List<String[]>. Notice the [], your method wants to return a list of arrays of strings, which is different from a list of strings.
Just change your return type to List<String>:
public List<String> fetchJSONChild()
Return type should be List<String> That's it
You've defined in your Signature a List<String[]>, so a list of String arrays.
But the List you instantiate is actually a List of Strings.
Please not that an ArrayList actually doesn't mean that it contains Arrays. (See https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html)
Either you change your method signature to public List<String> fetchJSONChild()
or you have to create Arrays of Strings within your method.
Best Regards
Datatype of child is List<String>. However return type of function is List<String[]> causing type mismatch.
Change return type of function to List<String> (and not List<String[]>) and it may work.
There is no point in having a multithreaded design for this program. Most likely when you fix the compilation problems that others mentioned your method will always return an empty List. I would suggest not to do any mutithreading in this case.

NullPointerException with an ArrayList inside of a HashMap [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am attempting to use an arraylist inside of a hashmap to create and iterate counters for different characters fed to the processLine method. I think I have declared all of the variables and the catch statements should handle the cases in which there isn't an entry in the hashmap, but I am still getting a NullPointerException on the curCounts.set(i, 1); line in the second catch statement. I've probably made some dumb mistake, but I can't figure out what it is.
HashMap<Character, ArrayList<Integer>> charCounts;
public DigitCount() { charCounts = new HashMap<>(); }
public void processLine (String curLine) {
int length = curLine.length();
char curChar;
ArrayList<Integer> curCounts;
Integer curCount;
for(int i = 0; i < length; i++){
curChar = curLine.charAt(i);
try {
curCounts = charCounts.get(i);
} catch (NullPointerException ex) {
curCounts = new ArrayList<>();
}
try {
curCount = curCounts.get(i);
curCount++;
curCounts.set(i, curCount);
} catch (NullPointerException ex) {
curCounts.set(i, 1);
}
charCounts.put(curChar, curCounts);
}
linesProcessed++;
System.out.println("---------------------------" + linesProcessed);
}
Edit: Yes, I did call DigitCount.
public static void main(String args[]) throws Exception
{
//creates an instance of the digitCount object and starts the run method
DigitCount counter = new DigitCount();
counter.run(args[0]);
}
if charConts doesn't contain i (as in charCounts.get(i)), then it won't throw a NullPointerException, it will return null. Therefore you should be using an if and not a trycatch as in:
curCounts = charCounts.get(i);
if(curCounts==null)
curCounts = new ArrayList<>();
Edit: Alternatively if you are using java 8 you can do
curCounts = charCounts.getOrDefault(i,new ArrayList<Integer>());
and it will automatically default to creating a new ArrayList if it doesn't contain one

Java Constructor by String parameters [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello my problem is that
DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= new String(v[0]);
interes= new List(v[1]);
}
This constructor is for be able to build and object by a file and I want transform the element v[1] in List(interes).
Thanks for your help guys.
You don't need to create a String with new String("") you can just set banco = v[0]
List is an Interface and can not be instantiated via a constructor. What you need is a ArrayList for example. But this class doesn't have a Constructor for a Strign neither. What is in that String v[1]?
I believe you have one or more elements (interes) and you wants to convert them into list of elements. You can use something like this.
import java.util.ArrayList;
import java.util.List;
public class DepositoBancario {
String banco;
List<String> interes;
public DepositoBancario(String s){
String[]v = s.split("[ :]");
Integer n= v.length;
if(n!=2) throw new IllegalArgumentException("Error"+s);
banco= v[0];
if(v[1] != null){
interes = new ArrayList<String>();
}
for(int i=1;i<n;i++)
interes.add(v[i]);
}
}
Note : Please consider the suggestion of markusw they are valuable.
First, You code won't compile unless You are using some custom implementation of List.
For what I can understand from You question it should be something like
import java.util.List;
import java.util.ArrayList;
public class DepositoBancario {
private String banco;
private List<String> interes;
DepositoBancario(String s) {
String[]v = s.split("[ :]"); // split input string by colon or space
if(v.length != 2) { // check if there are just two fields
throw new IllegalArgumentException("Invalid syntax, two fields expected: " + s);
}
banco = v[0];
interes = new ArrayList<String>();
interes.add(v[1]);
}
}

Categories

Resources