Is it possible to rename an ArrayList? [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
I was just wondering if there is a way to rename the variable assigned to an ArrayList... Or if I just need to create another one, just making it exactly the same.

Just create a new reference with the name you want and assign it from the old reference:
ArrayList original = ...;
ArrayList newList = original;
I should point out that since ArrayList is a reference type, original and newList are both pointing to the same data in memory. If you add an item to original or to newList, it is going to affect both. It is not creating a second copy of the ArrayList. It is a little difficult to understand what you are asking for, though.
If you are talking about refactoring your code to rename the variable across the entire application, then it sort of depends on what IDE you are using, but any good IDE will have this capability.

First, I would just like to point out that 'renaming' a variable is not really a concept that bares any resemblance to the way that changing a 'reference' or 'identifier' works. You can't change a variables identifier (kind of like a variable's name), but you can pass the variable's value to another variable with a different identifier.
When a variable refers to an Object or child of the Object class (such as ArrayList), your reference type variable holds data indicating the position of that object in memory. So passing that reference's data to another reference just means there are now two Object references that 'refer' to the same object in memory.
Technically speaking, if you wanted to give that object a name that you could use to identify it later with, this is possible by creating a custom class that extends ArrayList (or whatever object). For example;
public class NamedArrayList extends ArrayList{
private String listName = "default_name";
public String getListName(){
return listName;
}
public void setListName(String listName){
this.listName = listName;
}
}
Alternatively, you could create a Wrapper class which holds an ArrayList as well as a name for identifying it. Apologies if the last part is a little off subject, but I hope it helps.

You can try this
List<Double> original =new ArrayList<Double>();
List<Double> copy = new ArrayList<Double>(original);

You can't rename any variable while the programm is running.
But you could rename it while developing. Then compile and run.

If you mean by renaming using a different reference than you can simply do
ArrayList newListRef = oldListInstance;
//use newListRef thereafter
If you mean to change some of the elements retaining the order then -
ArrayList is dynamic in size. You can add and remove elements to and from specific index and ordering in retained. So no need to create separate List. If you want to change a specific element simply remove it and add new element at that index.
APIs
public E remove(int index)
public void add(int index, E element)

Related

add null in the list of model data arrays kotlin android [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 3 months ago.
Improve this question
Why can't I add null in the list of model data arrays in Kotlin language?
enter image description here
adapterPaging!!.setOnLoadMoreListener {
var customersModels: List<CustomersModel> = ArrayList()
customersModels.add(null)
}
var customersModels: List<CustomersModel> = ArrayList()
Your problem(?) here is polymorphism. You've defined customersModels as a List, which in Kotlin is explicitly immutable. You can't add things to it.
Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.
You're assigning an ArrayList to that variable, which is an object that does have the add method. And an ArrayList is a List, so you can do that. Like how a pencil is a writing tool that's erasable, if someone just needs something to write with, you can give them a pencil or a pen. All they've asked for is something that writes.
But the variable you're interacting with, customersModels, is explicitly a reference to a Kotlin List - a more restrictive subtype of MutableList*. It knows nothing about what that object actually is, just that it fits the immutable List type. That type does not have an add method so you can't call it. Same as how if you ask for a writing tool, you can't assume you'll be able to erase what you write.
So you have three options here (let's not get into reflection):
You can cast that variable to another type:
// or 'as ArrayList' if you really need to be that specific for some reason - you probably don't
(customersModels as MutableList).add(thing)
This is an unchecked cast - you're telling the compiler "hey I know what this is, you don't but you're just gonna have to trust me on this one". This is unsafe, because there's no protection, the compiler can't do any checking and force you to handle potential problems. (Don't do this)
A better approach is to actually check as you cast - there are two ways to do this in Kotlin:
// confirm the object's type - this will result in a 'smart cast' because the compiler
// can see that you're handling it safely, so it basically allows you to treat
// myList as that type
if (myList is MutableList) myList.add(thing)
// same deal but you can cast with a null fallback if it fails, then null-check the result
(myList as? MutableList)?.add(thing)
This is good for things where you handle a more general type, but you might want to get specific and handle different member types in different ways. Especially common if you're using sealed classes.
The last approach is to just use the appropriate type in the first place!
// MutableList, since you want to mutate it by adding stuff
var customersModels: MutableList<CustomersModel> = ArrayList()
customersModels.add(null)
You're creating a list you want to change - so that's a MutableList, and that's what customersModels should be. This kind of thing can be internal - you can expose that list as a List rather than a MutableList, so that other stuff that uses it sees it as a fixed, immutable list. If you've used LiveData you've probably seen this approach:
private val _myData = MutableLiveData<String>("hi")
val myData: LiveData<String> = _myData
myData is literally pointing at that MutableLiveData object, but because its type is just LiveData (the immutable kind) that means stuff that accesses that public variable see an object they can't change. Really they could cast it to MutableLiveData and mess with it, but it's less a security feature and more of an organisational thing. Make it clear how stuff is meant to be used, how you interact with it, etc. If you want to update, go through a specific function, that kind of thing.
So use List if it's just a list that's meant to be read, not written to. If it will/might be changed, use the MutableList type. This makes it clearer about what's going on.
Also, generally you shouldn't use explicit types like ArrayList - Kotlin has a bunch of functions to generate Lists and MutableLists, which makes it easier to reason about what you're doing and why:
val numbers = List(5) { it + 1 }
val greetings = mutableListOf("hi", "hey", "sup")
Notice I'm not specifying the type next to the variable, it's getting inferred by the function I'm using. So there's no "treat this mutable list as an immutable one" going on (unless you need to do that for a specific reason!)
Your customersModel POJO class must contain a nullable data type. and also you have to declare list as follow :-
var customersModels: ArrayList<CustomersModel?> = ArrayList() CustomersModel must be Then you will add null values to the list.

referring to this only (not attributes), possible? [duplicate]

This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 1 year ago.
Context (not strictly necessary to understand the question):
I have to implement a collection of elements. The class is called DocumentCollection. It is essentially an array of lists (a rudimentary form of a hash array), better formulated: an array of references to the first element of each respective list.
I already implemented a basic constructor, which takes an int as size of the array, and puts null initialized lists in each bucket.
One method to implement is removeAll. My first idea was to generate a new collection of the same size as the original one, and assign this to this newly created collection.
Below the code of the method.
public boolean removeAll(){
if(isEmpty()){
return false;
}
int size = buckets.length;
this = new DocumentCollection(size);
return true;
}
where buckets is the array.
As this is part of an assignment, I don't want to include the code of the whole class. This is enough for my question.
Intellij gives me the following error message (w.r.t. the line with this): variable expected.
Unfortunately this message is not eloquent enough for me to understand it.
Aside Note: yes, I could iterate over the array and assign null lists to them. That's not the point I am trying to make here
Question:
Am I doing something fundamentally wrong? In other words, is trying to give a new reference to the current object (i.e. this) illegal? Or can it be done, and I am simply using some wrong syntax?
You can't assign a new value to this since it is just a keyword to represent the current object along the class code, it is not a variable.
Beside's that, think of the semantics: you are inside the object asking it to become another object, that would be very tricky!
The closest you can get to that is to wrap some object as a field of your class, then you can assign a new instance to this field. Like this:
class MyObjectWrapper{
private MyObject myObject = new MyObject();
...
public void removeAll() {
this.myObject = new MyObject();
}
}
Check this related question: Why is assignment to 'this' not allowed in java?

Checking size of stack (ArrayList) in Java? [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'm trying to implement a stack with an Array List.
BlueJ tells me that "size" has private access in java.util.ArrayList even though the Array List is public, when I'm compiling.
int stackLength = stackStorage.size;
System.out.println(+stackLength);
And if I change the line to..
int stackLength = stackStorage.size();
the program compiles and I get a nullPointerExcetion when I run the function.
I don't understand why this is happening because a value cannot be manually assigned because the value needs to come from the stack size.
Any help appreciated, cheers.
You can't directly call for the variable (because it's a private field). You should use stackStorage.size() instead. Also make sure stackStorage is actually instantiated.
You most probably have:
ArrayList<Object> stackStorage;
However you must instantiate it somewhere like so:
stackStorage = new ArrayList<Object>();
This may also be done on the same line:
ArrayList<Object> stackStorage = new ArrayList<Object>();
Once you have created this ArrayList do note that it still doesn't have any elements in it. In order to actually add an Integer to the array simply do:
stackStorage.add(number);
And after you do that, if you call stackStorage.size() it should return 1, meaning there's one element in the ArrayList. If you wish to add more, simply use the add() method. Also make sure you add the same object as you instantiated it with. You can't store String in ArrayList<Integer> for example.
Full-code example:
ArrayList<Integer> stackStorage = new ArrayList<Integer>();
stackStorage.add(10); //Now has value `10` in `index[0]`
System.out.println("index[0]: " + stackStorage.get(0)); //Prints 10
System.out.println("stackStorage.size() = " + stackStorage.size()) //Prints 1
In your case replace Object with Integer if you wish to store integers. NullPointerException means your object is still null when you tried to call size(). This should solve your issue. If you're not sure what null is or don't quite understand what NPE(NullPointException) is I suggest reading about it and if you have further difficulties, posting it here.
That's because size is a private field and hence you don't have access to it, where size() is a public method that you can use. Therefore call size() to get the size of the ArrayList. The NullPointerException has nothing to do with size it is simple because your object is not initialized, make sure you initialize your objects before using them.
List<Something> list = new ArrayList<Something>();
size is a private variable
size() is a public method
For getting the size of the arrayList , you need to use size() and before calling size() dont forgot to intialize the array List like below .
List list = new ArrayList();

JAVA variable as 2 types [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
How can I create value of type String and also Collection?
I want someTimes put in this Strings and the othertimes put collections.
for example in javascript I would do
var k;
if (someBoolean){
k=1;
} else{
k=[1,2,3];
}
can I get this behavior of the variable in java, hack or something?
I found Solution: I created an interface and declear this Objects as this interface.
Java does not support union types; however, both of these types share the same base Object class, so you could assign either one of them to a variable defined like this
Object something;
something = "Hello World!";
something = new ArrayList(); // this is a collection.
Odds are that you probably were thinking of a Collection of Strings, in which case, you define it like Collection<String>
Collection<String> strings = new ArrayList<String>();
strings.add("Hello");
strings.add("World");
strings.add("!");
If that's not what you wanted, and you really want to sometimes store a String and sometimes store a Collection, remember that Java enforces strict type checking. This means that variables cannot just store anything, they must store something that is type compatible.
String and Collection are too different to be considered type compatible without some seriously bad programming (like using Object) or something even stranger.
You cant. String is a final class, meaning you cannot extend upon it. A String will only ever be a String. You can have a collections that contain Strings, but a String object will only have 2 types: Object and String.
You can have a class that contains a String (or a StringBuilder) and a collection, then use that class to store/receive from

Best way to share Java variables between classes [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 9 years ago.
Improve this question
I have an odd problem in Java. I can solve it but the solution seems inefficient.
I have a class, which simplified is
class Zot
{
double edges[];
}
The problem is that in many cases I want instance A and instance B to share ONE of the edge instances. In other words, instance A may allocate edge[2] and want instance B to share edge[2]. This is easy enough in that I can just set instance B to point at instance's A edge[2]. But how can I do it efficiently? If I allocate the edges[] in instance A, I can then simply assign B's instance to point to A. But often I only want to allocate a single edge (e.g. edge[2]) in A and then assign it in B. But in Java, one cannot (as far as I know) allocate a single member of an array (as one can in C++). Ideally, I only want to allocate the useful member and assign it. I could, of course, allocate all 4 members, assign the ones I need, then set the unwanted members to null and let GC clean it all up, but if there are hundreds or thousands of instances that seems clumsy.
Suggestions?
You can declare and allocate double edges[] outside of both classes, then pass this array as a parameter in the constructor into both of the instances that want to share it.
In Java an array is also an object. When you make an instance like double edges[] = new double[2]; edges will be passed around as a pointer, not as a copy.
This means if you make a change in the array in your class A, then class B will also see this change.
As I understand the question, you appear to want to share an individual element from your edges array between classes, and not share the whole array itself.
If your edges array was an array of Objects then this would be possible, and could make sense. However, since your array is a primitive array then there is no real concept of sharing an individual element.
You can assign an element of your array to equal the element of another array, but subsequent changes to the element in one array will not be reflected in the other array.
You can share the entire array between classes, in which case any changes will be reflected in both arrays (well, there is only one array, so both classes will see the changes to the single array that they both reference).
Most importantly:
When you declare an array of primitives in java, the memory is allocated immediately so there is no benefit (or mechanism) to declare only a single element of the array. So with your current data model, there is no reason for you to not predeclare your arrays since you cannot save space with them.

Categories