JAVA variable as 2 types [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 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

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.

List or Arrays for methods parameters? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm developing some methods here, some of them needs to have a list as a parameter.
I want to know if the appropriated way to do this is to use a List< T > or use an array [ ].
For example:
void method_name(List< String > arg)
void method_name(String arg[])
Which one is the recommended option?
Can someone help me?
Remember that List<T> is an interface. So passing a List as an argument makes your code more flexible since it does not depend on a specific implementation of a List.
So a method that takes a List<String> as a parameter can actually take an ArrayList<String> or a LinkedList<String> or any other implementation of the List interface. So it could even take a parameter of type MyList<String>, as long as the class MyList declares that it implements the List interface. The benefit of this is that if you wanted to change from using an ArrayList to a LinkedList elsewhere in your code, this method would still work.
By contrast, a method that takes a String[] can only take a String[]. So you would no longer have the benefit of being able to change the way you store these strings elsewhere in your code, without also having to change the method.
In terms of why Google might be using arrays as parameters a lot in their APIs, I think it really comes down to what they are using them for.
So I can't really recommend one or the other. It really depends on what the method does and what you want to do with the collection. For an overview of the key differences between modern programming structures, like Lists, and good old fashioned arrays, take a look at this answer.
There isn't a recommended or standard option. Lists and arrays are not the same object types at all. Both are used throughout Java. You can do either or both (overloading by type).
Keep in mind that there is a third option available namely
void method(String... params)
I can be accessed like an array however the size is flexible and you do not have to put everything into an array before the method call, but simple pass all your Strings.
method(string1, string2, string3);
i think more popular is array parameter.
void method_name(String arg[])
you can get any element from array andunderstand how many elements in array.
I think you should use List. it is slower, but it offers more flexibility and it's easier to use, especially if you are going to resize them.
If your parameter list is fixed just use as many parameters as you need
method(String parameter1, String parameter2)
I find using Arrays is cumbersome. There are several shortcomings:
No generics, see here
you have to copy the whole array into a new bigger one if you want to enhance it
and more depending on what you want to do
Especially when you want to use Lists in your code you have to copy your content all the time. So I'd say to go with List.
method(List<String> parameterList)
There is mentioned another way using variable parameter lists (varargs). However, be aware that you cannot pass the vararg parameter simply into another method using varargs as the vararg parameter is represented as an array and will be passed as such.
method1("first", "second");
void method1(String... params) {
//params[0] will be "first"
//params[1] will be "second"
method2(params);
}
void method2(String... params) {
//params[0] will be an array of Strings
//params[1] will give you an OutOfBoundsException
}
It completely depends on how you are going to use these objects.
Use List when
1) You are going to perform sorting, searching etc but not want to write much lines of code
2) If the size of elements may increase because Lists are resizeable.
Use Array if your requirement is not as above.

Java list default implementation? [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
If I declare a new list like this:
List<String> listExample = someFunction();
what list interface implementation will be used?
EDIT: Thanks for the answers so far. What is considered as the clean way to do this, should I always declare list with new?
As Eran commented that totally depends on what someFunction(); returns .Both ArrayList<E> and LinkedList implements List interface .
You can try ,
System.out.println("" + listExample.getClass());
to find out the which has been implemented. From docs,
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is
the object that is locked by static synchronized methods of the
represented class.
Whatever you are building e.g. LinkedList, ArrayList, Vector, Stack in and returning from someFunction() will be implemented with listexample. If you are using List interface reference, it has one benefit, that you can assign any type of object to it (LinkedList, ArrayList, Vector, Stack).
eg if u give
List listExample = new ArrayList();
Then the Object will be created for ArrayList and list is just an instance of listExample.
and you can use getClass() for that listExample to view

Is it possible to rename an ArrayList? [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 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)

Why those methods which are used has just one parameter although methods require values of two elements? [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
Class Alkio of my previous! question is chosen to do more methods.
Implement to the class in addition to the previous ones following
methods:
public boolean suurempiArvo(Alkio verrattava)
and
public int compareTo(Alkio verrattava)
Method suurempiArvo returns true, if the value of the object is
greater than value of verrattava. Method compareTo compares the
values of elements and returns an integer( negative, if the value of
the object is less that value of verrattava, zero, is values are the
same and otherwise positive)
Questions.
Why those methods which are used has just one parameter although methods require values of two elements? If I refer in the methods to verrattava by writing verrattava, how do I refer to object?
When you have a method
public int compareTo(SomeObject other) {
// needs implementation
}
You are comparing other with the current instance. That is to say, the reason why you do not need the second element in the signature is that the second element is already there, it's the object whose method is being invoked. You compare the members of other with the members of the present instance, basically this, in order to arrive at the proper result.
public int compareTo(SomeObject other) {
// assumes member variable foo
if (this.foo > other.foo) {
// you finish implementation
}
}
For clarification, if you were to invoke these methods, it would be something like
SomeObject first = new SomeObject();
SomeObject second = new SomeObject();
int result = first.compareTo(second);
So you pass the second object into the compareTo method of first. first then compares itself against the second (this vs. other).
Object would appear to refer to the instance of the Alkio class that you're calling the method on, so you'd refer to it using this.
You should refer to a tutorial on Java classes - and also the compareTo method of Comparable interface. The simple answer to your question is that you are dealing with two objects: verrattava' and the object itself, referrd to withthis, e.g.this.value1`.
Take a look at this article - it's not very well formatted, but does give you the idea - scroll down to an example at the bottom.

Categories