Hi I am a novice n just learning java. I was studying ArrayList n came accross this code for example {CODE1}.
I would like to use the same code but add a ArrayListDemo constructor n create methods such as displayList and removeElement.
I tried to find such examples but i did not understand them.
This is the code that i tried {CODE2} With my modifications please tell me where m going wrong.
***CODE1 {Example Code}****
import java.util.ArrayList;
public class AraryListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
System.out.print("Initial size of al : " + al.size());
System.out.print("\n");
//add.elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1,"A2");//inserts objects "A2" into array at index 1
System.out.print("size of al after additions " + al.size());
System.out.print("\n");
//display the array list
System.out.print("contents of al: " + al );
System.out.print("\n");
//Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.print("size of after deletions : " + al.size());
System.out.print("\n");
System.out.print("contents of al:" + al);
}
}
********CODE 2 {My Modifications}*************
class ArrayListDemo
{
ArrayList<String> al;//variable declared
ArrayListDemo() throws IOException//try constructor for this
{
al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n Enter Student Names");
for(int i=0;i<=5;i++)// will dispaly
{
al.add(br.readLine());
}
}
void dispList(ArrayList <String> al)
{
System.out.println("\n Display Student Names");
for(String str : al)
{
System.out.println("\t Name : "+str+"\n");
}
}
}
class DisplayArrayList
{
public static void main(String []args) throws IOException
{
ArrayList <String> al = new ArrayList <String>();
ArrayListDemo e = new ArrayListDemo();
e.dispList(al);
}
}
ArrayList <String> al = new ArrayList <String>();
ArrayListDemo e = new ArrayListDemo();
e.dispList(al);
In the above code, you are creating a new ArrayList al, and passing the same to dispList() method, which doesn't iterate, because the al has no elements.
I guess you wanted to iterate through the elements which you created within ArrayListDemo. So you may want to write dispList() method as below, which will now use ArrayList defined within the class
void dispList() //method parameter "al" is removed now and, al is the al of ArrayListDemo
{
System.out.println("\n Display Student Names");
for(String str : al) //here al refers to ArrayList defined within the class
{
System.out.println("\t Name : "+str+"\n");
}
}
It's not clear what exactly you're asking, but I note that you have a problem with your declarations (plural) of al: You have one ArrayList named al in your main, and you have another one that belongs to ArrayListDemo. You're reading values into the second one and then printing out the (empty) first one.
You really don't need a separate class with a constructor here. You can just have two static methods readList(List<String> al) and dispList(List<String> al). If you really do want to have a separate class, pick one place to store the List (either in main or in the class).
As a note, it's generally a good idea to use the most general type for variables and method parameters that you can. You're declaring an ArrayList, which is fine, but if you make your variable and parameters Lists, your code is more flexible.
The easiest (but not a prefered) solution to make your effort work is to pass the array to the displist() method that was filled by the constructor.
public static void main(String []args) throws IOException
{
ArrayListDemo e = new ArrayListDemo();
e.dispList(e.al);
}
Your code runs as following :-
ArrayList <String> al = new ArrayList <String>(); // Initialise an ArrayList of type string
ArrayListDemo e = new ArrayListDemo(); // Initialised class ArrayListDemo
class constructor reads data from user input and add to ArrayList a1 by br.readLine()
e.dispList(al); iterates the ArrayList instance a1 and print its output.
Related
import java.util.*;
class test2{
static void fun(int i,int arr[],List<Integer> l,int n,List<List<Integer>> res){
if(i==n){
if(l.size()!=0){
//System.out.println(l.size());
res.add((l));
//System.out.println(res);
}
//System.out.println(l);
return;
}
l.add(arr[i]);
fun(i+1,arr,l,n,res);
//System.out.println(l);
l.remove(l.size()-1);
//System.out.println(l);
fun(i+1,arr,l,n,res);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
List<Integer> l=new ArrayList<>();
List<List<Integer>> res=new ArrayList<>();
fun(0,arr,l,n,res);
System.out.println(res);
}
}
in fun function while i am adding a List to other List it is adding empty list i could find the reason can somebody help me this program is about finding the different combinations of given array
You can use res.add((new ArrayList<>(l)) instead of res.add((l)).
Why should use (new ArrayList<>(existing_list))?
When you update any primitive value then put in a list you can update again that primivite value. That does not change the value in list. But an object does not work like that. Well we can say it causes kind of pointer. When you update an object then it updates the values in its address. Let me show you a short example.
public class MyObject {
private List<String> list = new ArrayList<>();
public MyObject() {
list.add("added in Constructor");
}
public List getList() {
return list;
}
}
public static void main(String[] args) {
MyObject myObject = new MyObject();
System.out.println("--> Object list (Before added anything in main) : ");
myObject.getList().forEach(System.out::println);
List list = myObject.getList();
list.add("added in Main");
System.out.println("--> local list : ");
list.forEach(System.out::println);
System.out.println("--> Object list (After added a value in main) : ");
myObject.getList().forEach(System.out::println);
}
And the ouput is :
--> Object list (Before added anything in main) :
added in Constructor
--> local list :
added in Constructor
added in Main
--> Object list (After added a value in main) :
added in Constructor
added in Main
I did not set up a new Arraylist or create new one but my private list in MyObject is updated even if I just do changes in main function.
But instead of list If I returned new Array<>(list) then even if I update the list in main, my list would never change. Because I return another address with new Array<>(list). So you should add your list with another addres. I mean another Arraylist. So you can use res.add((new ArrayList<>(l)) instead of res.add((l)).
I'm trying to make an ArrayList that contains an object of another class, a name, and turn. something similar to the python's dictionary.
self.user1 = {"user":user1,"name":empty,"turn":empty}
so I made a class that has the 3 values.
class User{
public userInterface user1;
String name;
String turn;
public User(UserInterface user1,String name,String turn) {
this.user1=user1;
this.name=name;
this.turn=turn;
}}
and I'm trying to call it in the constructor of main class as following:
public class MainClassConstructon{
ArrayList<User> user1;
ArrayList<User> user2;
MainClassConstructon(UserInterface user1 ,UserInterface user2){
this.user1 = new ArrayList<>(new User(user1,empty, empty));
this.user2 = new ArrayList<>(new User(user2,empty, empty));
but it raises an error saying that: cannot infer type arguments for ArrayList<>.
ArrayList has three constructors:
public ArrayList(int initialCapacity)
public ArrayList()
public ArrayList(Collection<? extends E> c)
User is neither an int nor a Collection, and you're passing an argument so the middle constructor doesn't apply either.
But that's beside the point, your goal is to create a single list of users, so instead of doing what you're currently doing, you need to use only a single list, and simply add your users:
public class MainClassConstructon{
List<User> users; // Or ArrayList, doesn't really matter
MainClassConstructon(UserInterface user1 ,UserInterface user2){
users = new ArrayList<>(); // Diamond syntax, requires Java 7+
users.add(new User(user1, "", ""));
users.add(new User(user2, "", ""));
}
}
well i made it like this:
this.user1 = new ArrayList<>(Arrays.asList(new User(user1,empty, empty)));
and was able to access it by:
t.user1.get(0).name="bla bla";
you can try it like this
public class MainClassConstructon {
ArrayList<User> user1 = new ArrayList<>();
ArrayList<User> user2 = new ArrayList<>();
MainClassConstructon(UserInterface user1, UserInterface user2) {
this.user1.add(new User(user1, "", ""));
this.user2.add(new User(user2, "", ""));
}
}
I'm not a java developer but i suggest you try and look on Arraylist api.
Here is what i found online, sry if it doesn't help :)
import java.util.*;
public class ArrayListDemo { public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list System.out.println("Contents of al: " + al);
// Remove elements from the array list al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
I am trying to write a method that takes an ArrayList of Strings as a parameter and that places a string of four asterisks in front of every string of length 4.
However, in my code, I am getting an error in the way I constructed my method.
Here is my mark length class
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
And the following is my main class:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
ish.marklength4(words);
}
}
Essentially in this case, it should run so it adds an arraylist with a string of "****" placed before every previous element of the array list because the lengths of the strings are all 4.
BTW
This consists of adding another element
I am not sure where I went wrong. Possibly in my for loop?
I got the following error:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Marklength.marklength4(Marklength.java:7)
at MarklengthTestDrive.main(MarklengthTestDrive.java:18)
Thank you very much. Help is appreciated.
Let's think about this piece of code, and pretend like you don't get that exception:
import java.util.ArrayList;
public class Marklength {
void marklength4(ArrayList <String> themarklength){
for(String n : themarklength){
if(n.length() ==4){
themarklength.add("****");
}
}
System.out.println(themarklength);
}
}
Ok, so what happens if your list just contains item.
You hit the line if(n.length() ==4){, which is true because you are looking at item, so you go execute its block.
Next you hit the line themarklength.add("****");. Your list now has the element **** at the end of it.
The loop continues, and you get the next item in the list, which happens to be the one you just added, ****.
The next line you hit is if(n.length() ==4){. This is true, so you execute its block.
You go to the line themarklength.add("****");, and add **** to the end of the list.
Do we see a bad pattern here? Yes, yes we do.
The Java runtime environment also knows that this is bad, which is why it prevents something called Concurrent Modification. In your case, this means you cannot modify a list while you are iterating over it, which is what that for loop does.
My best guess as to what you are trying to do is something like this:
import java.util.ArrayList;
public class Marklength {
ArrayList<String> marklength4(ArrayList <String> themarklength){
ArrayList<String> markedStrings = new ArrayList<String>(themarklength.size());
for(String n : themarklength){
if(n.length() ==4){
markedStrings.add("****");
}
markedStrings.add(n);
}
System.out.println(themarklength);
return markedStrings;
}
}
And then:
import java.util.ArrayList;
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>();
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
Marklength ish = new Marklength();
words = ish.marklength4(words);
}
}
This...
if(n.length() ==4){
themarklength.add("****");
}
Is simply trying to add "****" to the end of the list. This fails because the Iterator used by the for-each loop won't allow changes to occur to the underlying List while it's been iterated.
You could create a copy of the List first...
List<String> values = new ArrayList<String>(themarklength);
Or convert it to an array of String
String[] values = themarklength.toArray(new String[themarklength.size()]);
And uses these as you iteration points...
for (String value : values) {
Next, you need to be able to insert a new element into the ArrayList at a specific point. To do this, you will need to know the original index of the value you are working with...
if (value.length() == 4) {
int index = themarklength.indexOf(value);
And then add a new value at the required location...
themarklength.add(index, "****");
This will add the "****" at the index point, pushing all the other entries down
Updated
As has, correctly, been pointed out to me, the use of themarklength.indexOf(value) won't take into account the use case where the themarklength list contains two elements of the same value, which would return the wrong index.
I also wasn't focusing on performance as a major requirement for the providing a possible solution.
Updated...
As pointed out by JohnGarnder and AnthonyAccioly, you could use for-loop instead of a for-each which would allow you to dispense with the themarklength.indexOf(value)
This will remove the risk of duplicate values messing up the index location and improve the overall performance, as you don't need to create a second iterator...
// This assumes you're using the ArrayList as the copy...
for (int index = 0; index < themarklength.size(); index++) {
String value = themarklength.get(index);
if (value.length() == 4) {
themarklength.add(index, "****");
index++;
But which you use is up to you...
The problem is that in your method, you didn't modify each string in the arraylist, but only adds 4 stars to the list. So the correct way to do this is, you need to modify each element of the arraylist and replace the old string with the new one:
void marklength4(ArrayList<String> themarklength){
int index = 0;
for(String n : themarklength){
if(n.length() ==4){
n = "****" + n;
}
themarklength.set(index++, n);
}
System.out.println(themarklength);
}
If this is not what you want but you want to add a new string "**" before each element in the arraylist, then you can use listIterator method in the ArrayList to add new additional element before EACH string if the length is 4.
ListIterator<String> it = themarklength.listIterator();
while(it.hasNext()) {
String name = it.next();
if(name.length() == 4) {
it.previous();
it.add("****");
it.next();
}
}
The difference is: ListIterator allows you to modify the list when iterating through it and also allows you to go backward in the list.
I would use a ListIterator instead of a for each, listiterator.add likely do exactly what you want.
public void marklength4(List<String> themarklength){
final ListIterator<String> lit =
themarklength.listIterator(themarklength.size());
boolean shouldInsert = false;
while(lit.hasPrevious()) {
if (shouldInsert) {
lit.add("****");
lit.previous();
shouldInsert = false;
}
final String n = lit.previous();
shouldInsert = (n.length() == 4);
}
if (shouldInsert) {
lit.add("****");
}
}
Working example
Oh I remember this lovely error from the good old days. The problem is that your ArrayList isn't completely populated by the time the array element is to be accessed. Think of it, you create the object and then immediately start looping it. The object hence, has to populate itself with the values as the loop is going to be running.
The simple way to solve this is to pre-populate your ArrayList.
public class MarklengthTestDrive {
public static void main(String[] args){
ArrayList <String> words = new ArrayList<String>() {{
words.add("Kane");
words.add("Cane");
words.add("Fame");
words.add("Dame");
words.add("Lame");
words.add("Same");
}};
}
}
Do tell me if that fixes it. You can also use a static initializer.
make temporary arraylist, modify this list and copy its content at the end to the original list
import java.util.ArrayList;
public class MarkLength {
void marklength4(ArrayList <String> themarklength){
ArrayList<String> temp = new ArrayList<String>();
for(String n : themarklength){
if(n.length() ==4){
temp.add(n);
temp.add("****");
}
}
themarklength.clear();
themarklength.addAll(temp);
System.out.println(themarklength);
}
}
I am attaching following code and i want to sort this as
class sort{
public static void main(String args[])
{String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List f=new ArrayList();
f.add(st);
Collections.sort(f);
System.out.println("after sortting "+f);
}
}
I want output as:
a
is
kiran
this
But i am getting an exception as:-
Exception in thread "main" java.lang.ClassCastException: java.util.StringTokenizer cannot be cast to java.lang.Comparableat java.util.Collections.sort(UnknownSource)atcom.sort.main(Sort.java:18)
Change your code. There are some mistakes you need to correct.
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List<String> f=new ArrayList<>(); // use String type list
while (st.hasMoreTokens()){ // add all tokens by iterating st
f.add(st.nextToken()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
Out put:
after sorting [a, is, kiran, this]
Now you are getting sorted list
The problem is here:
f.add(st);
You are adding StringTokenizer to the list, instead of adding the individual tokens. Changing the code to use generics would have helped: if you declare your List as List<String>, the code wouldn't compile, pointing you in the right direction:
List<String> f=new ArrayList<String>();
Add a while loop to collect tokens from st, and add them to f one by one.
P.S. Since this is almost certainly a learning exercise, I am not going to spoil the fun for you by completing your code.
You can also use hasMoreElements() and nextElement()
class sort{
public static void main(String args[]) {
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
ArrayList<String> f=new ArrayList<String>(); // use String type list
while (st.hasMoreElements()){ // add all by iterating st
f.add((String) st.nextElement()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
}
}
Consider using String.split() to split your string.
Class names should be nouns,
method names should be verbs or verb phrases,
and you should use generics.
public static void main(String[] arguments)
{
String input = "this is hootberry sause";
String[] inputArray;
List<String> inputList = new ArrayList<String>();
inputArray = input.split(" ");
Collections.addAll(inputList, inputArray);
Collections.sort(inputList);
System.out.println("Before sort: " + input);
System.out.println("After sort: " + inputList);
}
Expected output :
Cell-1 Cell-2
Cell-3 Cell-4
But the output that I am getting is :
Cell-3 Cell-4
Cell-3 Cell-4
Why is this happening?
import java.util.ArrayList;
public class Test {
public static void main(String... a) {
String[][] var1 = new String[] []{{"Cell-1","Cell-2"},{"Cell-3","Cell-4"}};
ArrayList<String> r = new ArrayList<String>();
ArrayList<ArrayList<String>> var = new ArrayList<ArrayList<String>>();
//Insering data into the ArrayList.
for(String[] row : var1){
r.clear();
for(String data : row){
r.add(data);
}
var.add(r);
}
//Print data to console.
for(ArrayList<String> r1 : var){
for(String cell : r1)
System.out.print(cell+" ");
System.out.println();
}
}
}
`
This is not unexpected at all: you add the same object, namely ArrayList r, to the ArrayList var twice. First, you add it when it has Cell-1 Cell-2, then you clear it, and then you add it with Cell-3 Cell-4. The problem is, when you call r.clear(), the array list that you added to var gets cleared as well.
You need to create a new ArrayList instead of clearing the existing one to fix this problem: replace r.clear() with r = new ArrayList<String>(), and the problem will go away.