Update element in Arraylist java - java

Sorry to repeat the question but i am new and looking the others answers didn't help me much.
I'd like to update my arraylist but i get stuck in an error that i cannot solve. Eclipse underlines the word set.
My code is:
private List<List> lists;
public void updateList(int index, string a) throws listException {
for(index = 0; index<list.size(); index++) {
list.get(index);
list.set(index, a);
}

You named the list as lists and trying to access list in the for-loop.
So your for loop should become like this:
for(index = 0; index<lists.size(); index++) {
lists.get(index);
lists.set(index, a);
}
Also it's String and not string and you will have to initialize the list.
So first change:
// Type should be String
private List<String> lists = new ArrayList<>();
And am not sure what is listException.
public void updateList(int index, String a) {
// Your rest of the code.

Related

How to get random string value without duplicate?

I want to fetch only a single company name and I want to fetch it only once. So if it already was fetched, it should not be fetched again.
Here is the code:
private static String[] billercompanies = {
"1st",
"TELUS Communications",
"Rogers Cablesystems",
"Shaw Cable",
"TELUS Mobility Inc",
"Nanaimo Regional District of",
"Credit Union MasterCard",
};
public static String GetBillerCompany(){
String randomBillerComp = "";
randomBillerComp = (billercompanies[new Random().nextInt(billercompanies.length)]);
return randomBillerComp;
}
Just shuffle the array you want using Collections
Collections.shuffle(List);
So simply create a list from your array
List<E> list = Arrays.asList(array);
Then shuffle it using the method above
Collections.shuffle(list);
Your list can be read from left to right as it was random.
So simply save the index
int currentIndex = 0;
public E getRandom(){
//If at the end, start over
if(++currentIndex == list.size()) {
currentIndex = 0;
shuffle(list);
}
return list.get(currentIndex);
}
Each time you want to forget the duplicate list you already used, simply shuffle the array again
Collections.shuffle(list);
Without index
You could simply remove the first value each time, once the list is empty, recreate it with the original array. As Ole V.V. pointer out, a List generated by Arrays.asList(E[]) doesn't support the remove methods so it is necessary to generate a new instance from it.
Here is a quick and simple class using this solution :
public class RandomList<E>{
E[] array;
List<E> list;
public RandomList(E[] array){
this.array = array;
buildList(array);
}
public E getRandom(){
if(list.isEmpty()) buildList(array);
return list.remove(0);
}
public void buildList(E[] array){
list = new ArrayList<E>(Arrays.asList(array));
Collections.shuffle(list);
}
}
And the test was done with this small code :
Integer[] array = {1,2,3,4,5};
RandomList<Integer> rl = new RandomList(array);
int i = 0;
while(i++ < 10)
System.out.println(rl.getRandom());
Make a copy in a List and remove the element when it was already fetched.
Arrays.asList(array) is not modifiable but you can wrap it in a full featured List.
List<String> billercompaniesList = new ArrayList<>(Arrays.asList(billercompanies));
String randomBillerComp = "";
Random random = new Random();
// first retrieval
int index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// second retrieval
index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// and so for

Interation of inner arraylist of arraylist of arraylists

I'm trying to make a arraylist of arraylists. My code is all over the place, I have just been adding stuff and trying trial by error. In the end what I'm trying to do is, say i have a car... it has speed, miles, mpg, and if they want to buy it add it to the arraylist of arraylists, and later be able to get a list of the cars owned, just to give you a idea of what I'm trying to do. idk if it helps, or maybe there's a better way to do it. I just need help with the iteration of the inner array, the rest i can figure out. Right now it just iterates the main arraylist and shows everything in there looking like a array. I rather use for loops then iterate class, but how ever it works is good for me.
public class Thelist {
String a ="aa";
String b ="bb";
String c ="cc";
static ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();
static int count=0;
ArrayList<String> listOfSomething1 = new ArrayList<String>();
public void gg(){
ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.add(a);
listOfSomething1.add(b);
listOfSomething1.add(c);
collection.add(listOfSomething1);
count++;
}
public void jk(int u){
//this one feel like i can make new arraylist and use for loop for the collection size and iterate each one
//but seems pretty hacky to me
ArrayList<String> lis = new ArrayList<String>();
lis.addAll(collection.get(u));
for(int i=0;i<lis.size();i++ ){
System.out.println("each "+i+" "+lis.get(i));
}
}
public void ll(){
System.out.println(collection.size());
System.out.println(collection.get(0).size());
}
public void ccc(String x,String y, String z){
this.a= x;
this.b=y;
this.c=z;
}
public void remo(int r){
collection.remove(0);
count--;
}
public void getcount(){
System.out.println("the count "+count);
}
public void showall(){
//this one shows all of the arraylist as arrays it looks like to me, I want each element
// feel like i should be able to add another for loop to iterate over listOfSomething1
//which is be add to the collection arraylist
// but it don't work tryed for each too
for(int i=0;i < collection.size();i++){
System.out.println("uoo "+collection.get(i));
}
}
}
public class MainActivity extends Activity {
static int oo = 1;
Thelist ll = new Thelist();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void woow(View v){
String gg = Integer.toString(oo);
ll.ccc("phi"+gg, "phil"+gg, "phily"+gg);
ll.gg();
oo++;
}
public void shoo(View v){
ll.showall();
}
}
Just use two nested for loops. The first iterates over the collection, yielding one ArrayList<String> per iteration. Take this list and iterate over it in the second iteration. For the sake of simplicity you can use for-each loops here:
for(ArrayList<String> cars : collection) {
for(String car : cars) {
System.out.println(car);
}
}
public void showall(){
for(int i=0;i < collection.size();i++)
for(int j=0; j< collection.get(i).size();j++)
System.out.println(collection.get(i).get(j));
}

Java - How to get the index of a given element in an array

I have an array of contacts like so :
public class Application {
private Scanner input;
private Contact[] contacts;
private int ArrayNum;
public Application() {
input = new Scanner(System.in);
contacts = new Contact[5];
ArrayNum = 0;
}
And what I want to do is enter a name of someone on the contacts list and if they are found on their list return their index like so:
System.out.println("Who do you want to remove?");
String name = input.nextLine();
for(Contact c: contacts){
if(c.getName().equals(name)){
//Get the index here
}
}
I tried researching this but no answer or guide seems to be very clear on this so I'm hoping that someone can explain this for me.
Thank you for looking
for(int index = 0; index < contacts.length; index++) {
if(contacts[index].getName().equals(name)) {
// use the index here
}
}
I don't think this code snippet needs any further explanation.
Use a for loop that uses a counter instead.
for(int i = 0; i < contacts.length, i++) {
if(contacts[i].getName().equals(name)) {
// do something with the index, i
}
}
You could use a counter
System.out.println("Who do you want to remove?");
String name = input.nextLine();
int remove_index = -1;
for(int i=0; i<contacts.length; i++){
Contact c = contacts[i];
if(c.getName().equals(name)){
remove_index =i;
}
}
Another alternative that may be helpful down the line is to use an ArrayList<Contact> instead of a c-style array (Contact[]). This class might add more handling complexity than it's worth, but it includes a lot of useful extra methods, including an int indexOf(<T> object) where <T> is the type you specified in your declaration (i.e., Contact for ArrayList<Contact> contacts).
Bad idea! You can't do that seriously, if you have an array. Of course you can set an index to null, but then you have to search for a null entry to reference a new contact within the array.
Note: you have an Iterator while writing
for(Contact c: contacts){...
So one option is to iterate by index, but it's a bad option. Better make your Array a Set. Then you might write:
for (Iterator<Contact> iter = mySet.iterator();iter.hasNext();) {
final Contact next = iter.next();
if(next.getName() == "NAME") {
iter.remove();
break;
}
Always use Iterator.remove()! Otherwise you will get Exceptions earlier than you wish :D

Using a returned ArrayList

I'm currently desperatly trying to get an ArrayList that I return from a function into a new ArrayList in my main function...
Here are the code snippets:
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
//filling bla
return al;
}
and here's where I call the function in the main function:
ArrayList<String> arr =permute("","abc");
arr unfortunately is empty, and I have no idea how to get it to work :(
Thanks in advance
EDIT:
Here's the full code:
import java.util.*;
class Problem24 {
public static ArrayList<String> permute(String begin, String end) {
ArrayList<String> al=new ArrayList<String>();
if (end.length() <= 1) {
String s=begin+end;
al.add(s);
} else {
for (int i = 0; i < end.length(); i++) {
try {
String newString = end.substring(0, i) + end.substring(i + 1);
permute(begin + end.charAt(i), newString);
} catch (StringIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr =permute("","abc");
System.out.println(arr.get(0));
}
}
Your ArrayList is empty but not null which means that the returning part worked. In oder to use the values from the method you need to fill the ArrayList inside the method.
ps: You should use List list = new ArrayList() or
List list = permute("", "abc") which is a simple version of dependency injection and a better design of your program.
You're not adding the items from the recursive calls.
Try adding the al.addAll to your permute call:
al.addAll(permute(begin + end.charAt(i), newString));
before returning the value make sure you are filling the al List
al.add(begin);
al.add(end);
al.add("any other string");
return al;
Obviously something in wrong with the // filling bla part.
I'd start with replacing your code in // filling bla with al.add("TEST"); and see if you even get something out.
Also your method is static and the source array isn't passed in, which suggest that either your code is supposed to permute those strings somehow. Are you possibly acting upon a static array (i.e. permute all elements between begin and end), and the source array is empty?
import java.util.*;
class Problem24
{
public static ArrayList<String> permute(String begin, String end)
{
ArrayList<String> al=new ArrayList<String>();
if (endingString.length() <= 1)
{
String s=begin+end;
al.add(s);
}
else
{
for (int i = 0; i < end.length(); i++)
{
try
{
String newString = end.substring(0, i) + end.substring(i + 1);
al.add(permute(begin + end.charAt(i), newString));
}
catch (StringIndexOutOfBoundsException exception)
{
exception.printStackTrace();
}
}
}
return al;
}
public static void main (String[] args)
{
ArrayList<String> arr = permute("","abc");
System.out.println(arr.get(0));
}
}
hope i corrected it the right way.
You call your method permute recurrently --- but you make no use of what it returns when it returns. In other words, you create a new array each time you call permute, but everything you get in for-loop is lost, as you are not passing it to next permute() calls --- eventually you return an empty array in which you didn't put anything.

how can we access individual int value from LinkedHashset<set<Integer>? Through string is it possible

I want to remove duplicates e.g.{ {1,2,3}, {2,3,1},{3,2,1},{2,1,3} } are duplicates of {2,3,1} or any one from given 4 sets.for this i converted 2D Integer array into LinkedHashSet which removed duplicates but when i am converting back to array (due to need in algorithm) i am unable to access individual elements.is it possible? if not, what is the other way.if yes what is problem in the code.given below.please resolve.
my own other thinking: as i think through string is it possible?
e.g { {2,3,1},{-3,-2,-4},........... } insert in Set making ArrayList of each 3 element set e.g.{2,3,1},{-3,-2,-4},{3 element}, .....and then parseInt to access individual element as {2},{3},{1},{-3},{-2},{-4},... will it work?
import java.util.*;
class demo
{
Integer[][] orderedpair3k={{1,2,3},{1,3,-2},{2,3,-1},{1,2,3},{1,-3,-2},{2,-3,-1},{1,-2,-3},{1,3,2},{-2,3,-1},{1,-2,3},{1,-3,2},{-2,-3,-1}};
Set<Set<Integer>> r = new LinkedHashSet<Set<Integer>>();
Object[][] a;
public void init_clauses()
{
removeDuplicate();
System.out.println(r);
backToArray();
for(int i=0;i<a.length;i++)
System.out.println(a[0][i]);
}
public void removeDuplicate()
{
int i=orderedpair3k.length;
for(int j=0;j<i;j++)
r.add(new LinkedHashSet<Integer>(Arrays.asList(orderedpair3k[j])));
}
public void backToArray()
{
ArrayList<Set<Integer>> arr=new ArrayList<Set<Integer>>(r);
a = new Object[arr.size()][3];
for(int i=0;i<a.length;i++)
a[i]=arr.toArray(new Object[i]);
}
}
public class sat
{
public static void main(String[] arg){
demo S = new demo();
S.init_clauses();}
}
//in the above code i am unable to access individual element because in the array Set is inserted as Object even i tried using ((Integer)a[i][j]).intValue() i think this is due to Arrays.asList(orderedpair3k[j]) how this problem can be resolve?
Seems quite straightforward:
Integer[][] result = new Integer[r.size()][3];
int c = o;
for (Set<Integer> s : r)
result[c++] = s.toArray(new Integer[3]);

Categories

Resources