FAQ Database Discussion Community


I added a rectangle to a shape Arraylist but the shape will not show up on the panel

java,arraylist,jframe,jpanel,graphics2d
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.ArrayList; @SuppressWarnings("serial") public class GUI extends JFrame implements ActionListener, MouseListener { private boolean drawLine = false; private boolean drawRec = false; private boolean drawOval = false; private final JButton line; private final JButton oval; private final JButton rectangle; private final JPanel buttonPanel; public...

Java - Create sublist from a list based on suffix

java,arraylist,collections,iterator,sublist
I'm trying to create sublists from a list based on the suffix. public class Test { public static void main(String args[]) { List<List<String>> subList = new ArrayList<List<String>>(); List<String> myList = new ArrayList<String>(); myList.add("Text_1"); myList.add("XYZ_3"); myList.add("ABC_1"); myList.add("Text_2"); myList.add("Text_3"); myList.add("XYZ_1"); myList.add("XYZ_2"); myList.add("ABC_2"); for (String item : myList) { List<String> tempList = new...

concurrent modification on arraylist

java,for-loop,arraylist,concurrentmodification
There are a lot of concurrent mod exception questions, but I'm unable to find an answer that has helped me resolve my issue. If you find an answer that does, please supply a link instead of just down voting. So I originally got a concurrent mod error when attempting to...

Looping Arraylist of Arrays java

java,arrays,jsp,arraylist,javabeans
I have a method in the model that creates an ArrayList array me from a resultset, I need is cross it from jsp, I could not do, any help? This is the code of the arraylist public ArrayList listar(){ String sql="select * from eventos"; ArrayList lista=new ArrayList(); try { st=con.createStatement();...

Set and Get multi dimensional arraylist to and from a bundle

android,arraylist,bundle
I have a multi dimensional arraylist and want to pass it to an activity. How do i do this? My code below is what i have so far... In my new activity i do stuff and pop the arraylist then bundle it. i then kill my activity and return to...

Put Integer ArrayList into a a single String

java,arrays,arraylist
Trying to put an ArrayList of Integers into a single string so I can create a popup window w/ the string of the values. Here is my attempt at it: } else if (control == show) { for(Integer s : array) { s1 += " " + s; } JOptionPane.showMessageDialog(null,...

Unexpected behavior of ArrayList inside ArrayList

java,arraylist
I am trying to use ArrayList<ArrayList<String>> to parse some fragment from web page but something goes wrong within my code: ArrayList<ArrayList<String>> x = new ArrayList<ArrayList<String>>(); ArrayList<String> s = new ArrayList<String>(); int z, y, w = 0; for(z=0; z<3;z++) { s.clear(); for(y=0;y<4;y++) { s.add(""+w++); } x.add(s); } for(ArrayList<String> tr : x)...

In a MapReduce , how to send arraylist as value from mapper to reducer [duplicate]

java,hadoop,arraylist,mapreduce
This question already has an answer here: Output a list from a Hadoop Map Reduce job using custom writable 1 answer How can we pass an arraylist as value from the mapper to the reducer. My code basically has certain rules to work with and would create new values(String)...

Control selected items of an ArrayList [closed]

java,arraylist
I have an ArrayList of Client: ArrayList<Client> clients = new ArrayList<>(); These clients are shown in a list, and the user can "select" one or more clients. That means that every client can be selected, or not selected, and there is no need to store this value out of the...

Trouble adding a row to a 2D ArrayList

java,arrays,netbeans,arraylist
I'm trying to read a line from a .txt file into a 1D Array, add two more elements to that Array based data from the previous ones, and store the new and larger Array in a 2D ArrayList called "dataArrayList", then repeat with the subsequent lines in the .txt file....

Generate list of names or words and output them in groups [closed]

java,php,arrays,arraylist
I am looking to take a list of words or names and output them into groups in a specific order via php or Java but have no idea how to do so. I will give an example with the order: (To clarify, this isn't homework. I am doing this for...

Read file in java until one row is found

java,arraylist
I have a file that looks like this: color1 red color2 blue color3 white end color1 blue color2 green end color1 black color2 white color3 red end I want to read this file and put the data between end in an ArrayList<ArrayList<HashMap<String,String>>> My code: public ArrayList<ArrayList<HashMap<String,String>>> getColors (String path) {...

I am trying to fetch data from database and place it in a ListView in android

android,sqlite,listview,arraylist,android-arrayadapter
I want to create a quiz app which contains 1 question and 4options for that I created a database from which the questions and options are fetched to 5 textviews using ListView. I surfed many tutorials and using a page from stackoverflow created it using ArrayList and Cursor but i...

How to store selected items of an ExpandableListView in an ArrayList

java,android,arrays,multidimensional-array,arraylist
I have a list of users inside of an ExpandableListView, for now I have 2 groups of list, now I'm trying to create an ArrayList that will add data as I click on the users, so if have 2 groups of schools and I click on a student of each...

List doesn't show data

android,arrays,listview,arraylist,parse.com
I have strings stored (objectIDs) in my internal storage. When I want to display the list of the IDs saved it works, however when I try to get the Names from Parse.com It doesn't show up on the list. This shows ObjectIds: public class UserListForHistory extends ListActivity { @Override protected...

ArrayList returns same value while looping

java,android,arraylist
I have an arraylist object of Drugs. I have 5 objects in the drugsList. So drugsList.size() returns 5. 5 drugs are in drugsList with drugName, description and category. I want to return 5 times a DrugsFragment with with name, description and category. What happens now is that it creates the...

How can I return an ArrayList from my AsyncTask?

android,arraylist,android-asynctask
I have an AsynkTask method on my MainActivity that it's the following: class chargeCars extends AsyncTask<Void, Integer, ArrayList<Car>> { protected void onPreExecute(){ } protected ArrayList<Car> doInBackground(Void... params) { ArrayList<Car> cars = new ArrayList<Car>(); cars.add(new Car(1,"Car1"); cars.add(new Car(2,"Car2"); cars.add(new Car(3,"Car3"); return cars; } protected void onProgressUpdate(){ } protected void onPostExecute(ArrayList<Car> c){...

Getting duplicate Elements using HashSet

java,android,arraylist,hashset
I am getting duplicate entries into ListView using ArrayList to populate and HashSet to remove duplicate elements, but still getting duplicate values like this: Delhi Mumbai Delhi Mumbai Here is my code which i am using to parse JSON data into List and to remove duplicate entries MainActivity.java: public class...

How can I check if an ArrayList contains an Object with a specific field value?

java,arraylist,override,equals,contains
I have an ArrayList of Objects. I want to see if that ArrayList contains an Object with a particular field. TeamBuilder.java public class TeamBuilder { public static void main(String[] args) { Team team = new Team(); team.addMember(new TeamMember("myID")); System.out.println(team.containsMember("myID")); //false } } TeamMember.java public class TeamMember { private String id;...

Java remove data that is duplicated

java,arraylist,hashmap
Is it possible to get all the distinct values in an arraylist or hashmap? Let's say for example I have elements on arraylist like this : 123, 123, 456, 123, 456, 000 And in HashMap : 123, test1 123, test2 456, test3 123, test4 000, test5 ...

ArrayList Remove Duplicate Elements

java,android,json,arraylist
I am parsing JSON data into ListView using ArrayList and now i would like to know How do i remove duplicate entries from ArrayList before populating it into ListView. Here is my JSON: { "data": [ { "city": "Delhi" }, { "city": "Mumbai" }, { "city": "Delhi" }, { "city":...

How to sort Arraylist consisting of pojo class in java

java,sorting,arraylist
I have POJO class Student like this class Student { private int score; private String FirstName; //Getters and setters ................. } I am creating ArrayList like this public static void main(String[] args) { List<Student> al_students= new ArrayList<Student>(); Student s1= new Student(); s1.setScore(90); s1.setFirstName("abc"); al_students.add(s1); Student s2= new Student(); s2.setScore(95); s2.setFirstName("def");...

Getting integer data from txt file in Java

java,file-io,arraylist
I want to read a text file which has String and a few integers related to that string. This is the class that I have to write my program in: public List<Integer> Data(String name) throws IOException { return null; } I have to read the .txt file and find the...

to generate a table with list using hbm file

java,hibernate,arraylist
I am new to Hibernate and trying to make an insertion of ArrayList<String> in DB using .hbm mapping file. I want no annotations to use. I made a search on how to insert ArrayList<String> and found working code from here. I was expecting that a new table containing entries of...

ArrayList cannot be converted to string.

java,arraylist,collections
Okay, I'm making a CD collection Program and everything was going well as I followed along my lesson but then I ran into the problem of wanting to make it show up in the jTextArea. I bet there is a simple solution but I cannot find one. I'm new to...

Java Threads with ConcurrentModificationException

java,multithreading,exception,arraylist,concurrentmodification
I'm currently working on my first multithreaded software - a program, which calculates prime numbers... Basically I create n (number of Threads) runnables. These runnables are added to an ArrayList. They check, whether a number is a prime. If the number is a prime I add it into an...

Android: Add item to top of arraylist [duplicate]

java,arraylist
This question already has an answer here: Java Arrays how to add elements at the beginning 7 answers I have a ArrayList of model class with some items in it. How to add new item to first position of ArrayList and shift others next to it....

Finding the desired amount of smallest Doubles in an ArrayList

java,arraylist,collections
I have an ArrayList filled with Double values, and based on user input (an int), I need to find the indices of the entered amount of smallest Doubles from this List. For example, if the user were to type in 5, and the ArrayList looked as such (is actually much...

Java convert from String to int from ArrayList

java,arraylist
I have this method where I want to take the integers from an ArrayList and store them to a int but it gives me this error message: Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer Heres the code: public static void convertList() { ArrayList list= new ArrayList();...

Issue reading and saving lines from .txt file in Java

java,arraylist,io
Objective & Issue Objective of the task I am trying to accomplish is to locate and read a text file from a provided path then copy each line of the text file into a ArrayList<String>. This "ApplicationFileReader" object is created in some control class by calling the constructor which takes...

Java ArrayList indexOf returns -1

java,arraylist,equals,indexof
I have a strange problem with my code. Heres the code I test the Chunk class with: List<Chunk> chunks = new ArrayList<Chunk>(); chunks.add(new Chunk(1,1,1)); System.out.println(chunks.indexOf(new Vector3i(1, 1, 1))); And here is the Chunk class' equals method: public boolean equals(Object object) { System.out.println("Test _1_"); if (object != null && object instanceof...

all the names are not fetching from arraylist

json,arraylist
Json file show on arraylist, I want to show all the names from the arraylist from the json file. try { JSONArray root = new JSONArray(json); for (int i = 0; i < root.length(); i++) { JSONObject att = (JSONObject) root.getJSONObject(i); name = att.getString("nm"); list.add(name); } for(int i = 0;...

part arraylist to 3 strings part

java,arraylist
I am trying to split my arrayList which has the size 3n to 3 part (with size n each),but I am getting just the first one. How can I fix that? [1,2,3,4,5,6,7,8,9] ==> [1,2,3][4,5,6][7,8,9] I appreciate any help. List<RootCreator> mainSublist = new ArrayList<RootCreator>(); int number = mainList.size()/3; for(int i= 0...

Efficiently adding element to the top of the list

java,list,arraylist,enums,linked-list
I have an ENUM like this from which I always get what is my localFruit which can be either APPLE or ORANGE or BANANA. public enum Fruits { // it can have more elements here APPLE, ORANGE, BANANA; // some code } So let's say if APPLE is my localFruit,...

changing properties of item in arraylist

java,arraylist
I’m developing a application that will borrow a car to the user, user can choose from the fleet available. Unfortunately when registration number is typed in and name of the borrower is given, program assigns that person to the first entry in arrayList that has been added. I’m not sure...

Unable to populate ListView from ArrayList

java,android,json,listview,arraylist
ChooseCategory.java public class ChooseCategory extends ListActivity { private ListView lv; //ArrayAdapter<FoodStores> arrayAdapter; private ArrayList<FoodStores> storefoodList; private String URL_STORES = "http://10.0.2.2/get_stores.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); lv = (ListView)findViewById(R.id.list); storefoodList = new ArrayList<FoodStores>(); new GetFoodStores().execute(); } private class GetFoodStores extends...

Need help to understand deserialization with ArrayList in Java

java,serialization,arraylist,casting,deserialization
I want write an ArrayList to a file and then read it back again. The list is going to hold Integer objects. Serialization seems to be working fine but I'm having trouble deserilaizing. More specifically I can'get the casting right. The serialization: ObjectOutputStream ou = new ObjectOutputStream(new FileOutputStream(new File("load.dat"))); ArrayList<Integer>...

Arraylist with Multi Dimentional for loops

vb.net,multidimensional-array,arraylist
Friends I have a serious issue at present and Honestly I have no idea as to why this isn't working as expected. I am more a custom to C# than VB can anyone help with the following Code Example Please note that the String is passed from other classes and...

Java - name of ArrayList?

java,arraylist
I've the following question: Why is it not necessary to use a name of the list before the add-statement (add (pipedInstanceIterator.next())) ? Thanks. public class InstanceList extends ArrayList<Instance> implements Serializable, Iterable<Instance>, AlphabetCarrying ... public void addThruPipe (Iterator<Instance> ii) { //for debug Iterator<Instance> pipedInstanceIterator = pipe.newIteratorFrom(ii); while (pipedInstanceIterator.hasNext()) { add (pipedInstanceIterator.next());...

Can't add JSONObjects into an array

java,json,parsing,arraylist
I am using JSON simple to parse a JSON file. When I do so I get a JSONArray. But when I try to iterate through it and get its JSONObject elements I get an error. This is my code: JSONArray jsonData = (JSONArray) jsonParser.parse(reader); List<JSONObject> elementsList = new ArrayList<JSONObject>(); for...

Socket don't save values in list

java,multithreading,sockets,arraylist
I'm new in network developing in Java and I want to create a simple Socket server, that get values from client and collects all of them in ArrayList. I wrote an example code, but in server side it not collecting the strings. This is my server side: Server public class...

ArrayList in the end is null

java,arraylist
I am collecting from a form some values, which I add them to an ArrayList and then I create an object. ArrayList<Integer> machines = new ArrayList<>(); ArrayList<WorkPosition> workPositions = new ArrayList<>(); for (int i=1; i<=positions; i++){ fname1 = "position"+i+"-1"; fname2 = "position"+i+"-2"; fname3 = "position"+i+"-3" m1 = Integer.parseInt(request.getParameter(fname1)); m2 =...

How do I add different inner classes to an ArrayList?

java,arraylist,inner-classes
So, I'm building a very basic program based on the Warhammer 40k tabletop game as an extra credit assignment for my Comp Sci class. I get to develop the specs and then I implement the specs. In this game, I have a class Army that has an ArrayList of class...

adding elements to arraylist using a loop

java,user-interface,arraylist
My problem is very simple but i can't find the way to solve it. Basically i want to create an Arraylist and add elements to it using a loop(up to as many elements as i want). i'm using the netbeans gui, and whenever i press a button "add" i want...

LinkedHashMap vs ArrayList with Bluetooth Scanning and ListView

java,listview,arraylist,linkedhashmap
I have a little bit of a confusion when it comes to what is considered the better implementation. One the one hand, LinkedHashMap provides the following benefits: Prevents duplicate items (I need to be able to prevent a scanned Bluetooth device to not repeatedly enter the list.) Provides easy access...

ensureCapacity() for inner ArrayList

java,arraylist
I have a 2-dimensional ArrayList Object private ArrayList<ArrayList<Short>> VOL_2D = new ArrayList<ArrayList<Short>>(); Now I want to call .ensureCapacity() on both the outer list and all the inner lists (The number of inner lists is know, but they are not initialized yet). For the outer list it is easy, I just...

Sum of ArrayList for different types

java,arraylist
Is it possible to write a single method total to do a sum of all elements of an ArrayList, where it is of type <Integer> or <Long>? I cannot just write public long total(ArrayList<Integer> list) and public long total(ArrayList<Long> list) together as there will be an error of erasure, and...

Adding to arraylist unexpected behavior

java,arraylist
I'm not sure what is going on here. Any enlightenment would be greatly appreciated. ArrayList<Integer> al = new ArrayList<>(); for(int i = 0; i < 10; i++) al.add(i); for(Integer i : al) System.out.println(al.get(i)); al.add(2,8); //should add the value 8 to index 2? System.out.println(); for(Integer i : al) System.out.println(al.get(i)); Output 0...

Multiple Strings into Arraylist

java,android,arraylist
I am trying to add Strings dynamically into an ArrayList along with index position and then pass on the Arraylist as an extra in Intent.The process runs fine for first time and on next call to this activity would end up in Index out of bounds Exception. Please see the...

Why I get java.util.ConcurrentModificationException error?

java,android,arraylist,android-asynctask
I'm having troubles with this code: protected void onPostExecute(ArrayList<Example> examples){ for(Example i : examples) { customAdapter.add(i); } listExamples.setAdapter(customAdapter); } where listExamples it's a ListView that I have in my mainActivity layout. The error that it gives to me it's the java.util.ConcurrentModificationException error. I know that it happens when you modify,...

How to give different array list for each key when implementing HashMap>

java,dictionary,arraylist,hashmap,multimap
I want to have a different array list for each key when I use HashMap>. I would like to store the sentence id as a key and words of the sentence in array list. To do that I did the following: //I used the multimap for this task and it...

Clear all selected items in a gridview

java,android,gridview,arraylist,expandablelistview
I have a gridview inside a ExpandableListView with CHOICE_MODE_MULTIPLE, I'm trying to deselect all items when I press a button, but the way I'm doing it it is only unselecting the last item, how can I clear all of them? @Override public int getCount() { return child.size(); } @Override public...

Store patient information into text file and load it afterwards

java,arrays,arraylist,text-files
We got the task to write a simple Hospital Management System. The user is able to enter the patient information such as name, gender, date of birth and disease. The data is stored in an ArrayList and saved into a textfile. Now to my problem: I need to display all...

How do I get the variables in a column from java and sql?

java,mysql,jdbc,arraylist
So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example: Names Test Test1 Test3 River World Etc I want to get all of that into an array list. Thanks for the help!...

Guice : Inject an ArrayList of Strings

java,arraylist,guice,inject
I'm trying to inject an ArrayList of Strings with the help of Guice. I want to show a panel with many RadioButtons (for example) where an user can select some services to activate. Once selected, I would like to get all the names of the selected services and add them...

Removing duplicates from arraylist using set [duplicate]

java,arraylist,set
This question already has an answer here: Common elements in two lists 4 answers Have 2 sets with duplicates set1 ={1,2,3,4,5} set2 = {1,3,6,7} and the result should be set3 ={2,4,5,6,7} Please let me reiterate that I want to use Set interface and the result set should be ordered...

Insert values from arraylist into database

java,jdbc,arraylist
I use addbatch() and executebatch() to insert values from ArrayList into database. But when I run the code this error message appeared: Exception in thread "main" java.sql.BatchUpdateException: Duplicate entry '5' for key 'PRIMARY' at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2020) at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451) This is the data: 1 A R1 7 A R1 2 B R1...

Trying to calculate the average in an ArrayList

java,arraylist
I'm trying to write some code which takes in any number of entries and stores it in an ArrayList given a specific condition. What I'm not able to do is find the average of the values stored in the ArrayList. Here's the code written so far: import java.util.ArrayList; import java.util.Scanner;...

how to draw infinite amount of sprites?

java,arraylist,android-studio,sprite
i am a beginning programmer and I am making a flappy-bird kind of game in android studio. I am stuck at making missles coming in from the rightside of the screen. Any hints,tips,tricks on how to approach this problem? I thought myself of making a list of sprites and trying...

How to get certain information out of arraylist grouped into other lists in Java

java,arraylist,text-files,group,information-retrieval
I wrote a program, that reads multiple (similar) textfiles out of a Folder. Im splitting the information by space and store everything in one arraylist which contains data kind of this: key1=hello key2=good key3=1234 ... key15=repetition key1=morning key2=night key3=5678 ... Now I'm looking for a way to get those information...

implement class object and Arraylist

java,file-io,arraylist
I am new to Java and I have a task to do. I have created a class (Company) which looks like this public class Company implements Serializable { private String companyName; private String companyCode; private int shareNo; private double closingRate; /** * Initializes a newly created company object so that...

JAVA RMI get pass ArrayList element

java,arraylist,get,element,rmi
I have a server that contains an ArrayList in " ServerInfo " and when I try to take from ClientRMI an element of the ArrayList(in ServerInfo) for example adf.getSGM ( 0 ).incrementCount( ) ; "count" does not increase it's as if every time I call it instantiates a new class...

Mirror method using arraylist

java,arraylist
I am writing a "Mirror" method which duplicate the message backward, and add to the original ArrayList if the size is even. public ArrayList<Integer> mirror(ArrayList<Integer> mr) { if (mr.size() % 2 == 0) { for (int i = mr.size() - 1; i > 0; i--) { mr.add(mr.get(i)); } } return...

Concurrent modification exception when using iterator? (Java)

java,debugging,arraylist,iterator
I am trying to write code for the simulation WaTor in which sharks and fish eat each other and simulate population control etc. Anyways, the problem I am having is that i keep getting a concurrect modification exception even when using an iterator. Here is my code: private void updateSharks()...

How to get range of 10 items from the arraylist in java? [on hold]

java,arrays,arraylist,pagination
I have a dynamic arraylist where the values are coming from the database. Let's say 85 records are selected from the database and inserted in to the database. Now I need to display those records in a pagination format with limit of 10 rows per page. How can I fetch...

Preventing the user from entering identical elements(within a malfunctioning try catch)

java,if-statement,arraylist,try-catch
So the following code is like a simple game,where the objective to to guess the correct numbers(which are 1 to 5).Anything else is incorrect and the user is given a warning message if they enter similar numbers.The comments would explain the loops and variables declared. The only problem I have...

Sublists of a list in java

java,list,sorting,arraylist,sublist
There are N buildings in a certain one-dimensional landscape. Each building has a height given by hi,i∈[1,N]. If you join K adjacent buildings, they will form a solid rectangle of area K×min(hi,hi+1,…,hi+k−1). Given N buildings, find the greatest such solid area formed by consecutive buildings. Input Format The first line...

Jsoup ArrayList and LinkedHashMap Combo

java,android,arraylist,linkedhashmap
The code I've written uses jsoup to go to a site, views all the paragraph headings, then saves them to an ArrayList called headingList. Here's the tricky part. I've got a map that takes Strings as the keys and ArrayLists as the values. The code is designed in a way...

Detect and Remove duplicates in ArrayList?

java,android,arrays,multidimensional-array,arraylist
I have an array with 2 positions, each one contains a list of "ids_alunos", the first position has ids_alunos: "1,2,3" and the second:"4,5" but what is happening when I add the ids in my array is this, the first position gets "1,2,3" values and the second: "1,2,3,4,5". why is this...

How to remove a value from a hashmap?

java,android,arrays,dictionary,arraylist
The thing is, I have an ExpandableListView with 2 groups, inside of each group I have some users and when I click on these users I get their ids and add to a HashMap of strings, now I'm trying to remove these ids when I click on them for the...

Why is my ArrayList throwing an IndexOutOfBoundsException exception?

java,arraylist
I'm writing this method to create a shuffled deck of cards: public static ArrayList<String> shuffle() { String cards[] = {"Two of Spades","Three of Spades","Four of Spades","Five of Spades", "Six of Spades","Seven of Spades", "Eight of Spades", "Nine of Spades", "Ten of Spades", "Jack of Spades", "Queen of Spades", "King of...

Accessing elements in Multidimensional Array of ArrayList

java,arraylist
public static void main(String[] args) { new T1(); ArrayList<Integer>[][] b = new ArrayList[2][3]; b[1][2] = new ArrayList(); b[1][2].add(1); //print [1] System.out.println(b[1][2]); } I made a 2D array of ArrayList. How can we check if a number has been added at a particular index of the ArrayList using the if statement?...

Calling methods of an object that is already stored in an ArrayList

java,arrays,object,arraylist
Everything works so far in my program but I'm having trouble with this section of my code: else if(input.equals("2")) { System.out.println("Enter the stock symbol:"); symbol2 = in.next(); System.out.println("Enter the number of shares you wish to sell:"); sellshares = in.nextInt(); String tempsymbol = ""; for(int i=0; i<array1.size(); i++) { tempsymbol =...

Problems with prime number generator, using ArrayList

java,arrays,arraylist,primes
I have been having a heck of a time trying to make a prime number generator work. It's supposed to list the first 100 primes, so sieving means either cheating and looking up an artificial limit to the composites, or creating a bunch of needless arrays of composite numbers. Just...

Java catch the ball Game

java,swing,loops,arraylist
I am having trouble with my Java project for school. The plan was to make a simple game where you need to catch the ball and if you catch the ball you will get points. At the moment I have 2 problems: I have no idea how I make the...

Java Swing Displaying Large Amounts of Data from ArrayLists

java,swing,arraylist,large-data
I cannot provide code because this is an abstract problem that I am currently facing. I am working on a program which allows a user to track players from games. The program essentially stores a players profile information in an ArrayList. One feature of my program that I would like...

Difference in performance of adding elements in Treeset directlt vs transferring from arraylist?

java,arraylist,data-structures,treeset
I want to know the difference in performance between adding element in a TreeSet one by one versus adding elements in ArrayList and then transferring to TreesSet by .addAll() method. I know TreeSet uses Red–black tree as its data structure. Just want to know the basic internal workings of this...

Adding a RadioButton to a itemView adapter within a ListView

listview,arraylist,radio-button,barcode,selecteditem
I wonder if anyone can help with this , please? This Code below is ListView adapter to enable a single itemView to which all works well. Iam able to show with this adapter the barcode number and the time of the item that is read by a barcode reader with...

Syncing a JTable with ArrayList of Objects values in Java

java,swing,arraylist,jtable
My program has a JTable which displays information about a student. e.g. Columns contain: "Name", "Surname", "Age", "Year" I also have an Object class for students as follow: public class Student { private final String name; private final String surname; private final int age; private int year; public Student(String name,...

Get the index of the element in the arrayList

java,arraylist
I am trying to get the index of 466 in the arrayList minuteList [288, 318, 346, 376, 406, 436, 466, 1006, 1036, 1066, 1096, 1126, 1156] but I am getting this error: java.lang.IndexOutOfBoundsException: Index: 466, Size: 13 at java.util.ArrayList.rangeCheck(ArrayList.java:635) at java.util.ArrayList.get(ArrayList.java:411) at com.pdf.PDF.refill_time_table(PDF.java:155) at com.pdf.PDF.main(PDF.java:54) I have debugged it and...

How to remove Sprite/Object from ArrayList? [duplicate]

java,arraylist,libgdx,sprite
This question is an exact duplicate of: Removing sprite when Touched 1 answer I created an ArrayList just for the sprites that needs to be removed, when the sprites are touched they are added to the ArrayList. //drawing the enemy that spawns and making them move public void draw(SpriteBatch...

How replace one list items with another in java?

java,arraylist,collections
I have two array lists, Can it possible to replace the one list items with the second list. ArrayList<String> a = new ArrayList<String>(); ArrayList<String> b = new ArrayList<String>(); a.add("testone"); a.add("testtwo"); a.add("testthree"); b.add("demoone"); b.add("demotwo"); System.out.println("List values are: "+ a); Is there any way to replace the first list with the second...

ArrayList of String Arrays save last record only

java,arrays,arraylist
I need some help with my ArrayList in Java. I spent long time debugging, but still. The problem is - I save some data from database to string array and save this array to ArrayList, in the output it saves only last element multiple times. Looks like it simply rewrite...

How to display extra info in custom info adapter with Arraylist(populated with data from KSOAP Webservice) using hashmap

java,android,arraylist
I made a custom info window that displays 5 info (Hospital name, Address, Fax, Mobile and Landline), I successfully displayed the Hospital and Address with the use of Title and Snippet when being pressed but not with the 3 last data. some blogs says I should use Hashmap to display...

I never figure out the correct way to create an 2D ArrayList

java,arrays,arraylist
List<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N); List<List<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N); ArrayList<ArrayList<Planet>> NAME = new ArrayList<ArrayList<Planet>>(N); I can't tell what's the difference of these three expressions. I realized later that maybe List is for declaration because its an interface while ArrayList could be used for initiation, as it is a class....

POSTing `JSON` to an `ArrayList` gets the response “Request JSON Mapping Error”

json,arraylist,resteasy
I have a problem POSTing JSON to an ArrayList I have a class Plan public class Plan { private String planId; private String planName; : : } and an ArrayList of Plan - PlanList public class PlanList { private List<Plan> plans = new ArrayList<Plan>(); : : } I have POST...

Java .contains not actually searching my arraylist

java,arraylist
Edit: re-writing the whole question. public static int search(ArrayList addressBook)//handles all search functionality { Scanner input = new Scanner(System.in); String searchModifier;//declaring variables int noEntry = -1; System.out.print("\n\nPlease enter value to search for: ");//empowering the user searchModifier = input.next();//gathering searchModifier System.out.print (addressBook); if(addressBook.contains(searchModifier))//if their searchModifier is found return addressBook.indexOf(searchModifier);//return that index...

ArrayList from java to C#

java,c#,list,arraylist,equivalent
This is Java code, how can I do this with C# static ArrayList<ArrayList<String>> test= new ArrayList<ArrayList<String>>(); test.get(index).add(s[1]); ...

How do I read a text file into an arraylist and delete lines that contain certain words (java)?

java,arraylist
I am trying to make a program that reads a text file named text.txt into an arraylist. And then after that it must remove any lines of the text that contain the words "I Love Cake" So say this is the text from the file: I love cake so much...

Java - order things in an arraylist according to an atribute

java,sorting,arraylist
Hi, i have an arraylist, lets call it "callcenterList" in that arraylist i will add objects of the "Call" class. The "Call" objects have different atributes, some of them are "Status", "Month" and "Day" (Month and day when the call was received and the Status of it). The status could...

ArrayList prints “5.0E-4%” instead of 0.0005

java,arraylist,jradiobutton
I have this button JRadioButton rdbtn1CE38 = new JRadioButton("> 100 %"); rdbtn1CE38.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CE.set(37,0.0005); label_CE.setText("CE:"+(CE.get(0)+CE.get(1)+CE.get(2)+CE.get(3)+CE.get(4)+CE.get(5)+CE.get(6)+CE.get(7)+ CE.get(8)+CE.get(9)+CE.get(10)+CE.get(11)+CE.get(12)+CE.get(13)+CE.get(14)+CE.get(15)+CE.get(16)+ CE.get(17)+CE.get(18)+CE.get(19)+CE.get(20)+CE.get(21)+CE.get(22)+CE.get(23)+CE.get(24)+CE.get(25)+...

Search for key in Map when the values are in ArrayList [closed]

java,arraylist,collections,hashmap,key-value
I am new to the collections in Java , I have a HashMap<String, List<String>>. I want to search for a key from the Map when a value is given. The map stores the data of a state as key and its cities as the list. So it is assumed that...

Searching an arrayList generated by an audio recognition

java,android,audio,arraylist
I am working on app that take the audio of the user and save them in an arrayList, then searching this array list to see if the desired word generated by the google audio API exists, so we can do actions. The action that I wanted is removed and replace...

Get the second same value in the ArrayList

java,arraylist
I am trying to add marker New direction to the arrayList mergeArray when I found the second 3 value in the buffer arrayList but I am always getting the first 3 value in the ArrayList. How can I get the second one after Amsterdam? I appreciate any help. output: paris...

add multiple value in array list

java,arraylist
i have created a class employee.it has four variables name,id,salary,city.i have made a array list of the employee class object.When i run the file it only shows the defaullt values.But i want to add more than one value in my array list.what should i do?please help me to solve this...

How to put this cursor data in ArrayLists - AndroidStudio

android,arraylist,android-studio
I have a cursorLoader which returns a cursor with this data: 0 { [email protected] about=Party } 1 { [email protected] about=Paaarty } 2 { [email protected] about=activity 2 } 3 { [email protected] about=activity 3 } 4 { [email protected] about=activity 5 } How can I save the emails in an ArrayList called emails...

java.util.NoSuchElementException while using StringTokenizer in java

java,arraylist,stringtokenizer
I am recently doing simple project on file reading, writing and comparing string in core java. I have used StringTokenizer for parsing each elements in line. but while doing so, i encounter following error message. Any help regarding this, thanks in advance. Error message: Exception in thread "main" java.util.NoSuchElementException at...

Accessing a char in a String in an Arraylist

java,string,arraylist
I can access and print a string from my arraylist list.get(0).getLastName(); but I can't access a char: list.get(0).getLastName().charAt(0); Even if I set list.get(0).getLastName() equal to a variable like str, I can print str fine, but if I try str.charAt(0), it never returns anything that I can print or work with....

Using user input value to display a specific object from an array list

java,arraylist
I am trying to create a program where the user inputs animal pertinent values, which then create animal Objects, which are then saved into an array list. The area I am having trouble with is shown below. After the Array list is populated, I cannot figure out how to use...

get specific value from ArrayList in C#

c#,asp.net,arraylist
I am using ArrayList in Asp.net I want to extract specific items . My code is ArrayList items = (ArrayList)Session["mycart"]; foreach(var v in items) { } but this is not working . I want to get value like v.myvalue; My arralist is filled with several items coming from prevoius page....