As a newbie in Kotlin, i want to ask a question. Let’s say that i have class Dog like below,
data class Dog(val breed : String, val gender : String, val name : String, val age: Int){}
I want to make 1000 instances of this Dog class and add all of instances in an arrayList and later i will use this list in different activities. Imagine that I have an activity which only shows Labradors . So i have to take that arrayList which contains all of my Dogs and filter the breed according to Labrador and show the user.
As i read in articles i think this is an expensive way but i don’t know what the efficient way is to do this. Cause i will create all instances manually like below.
fun dogMaker(){
val dog1 = Dog("example","example","example",1)
val dog2 = Dog("example","example","example",1)
val dog3 = Dog("example","example","example",1)
val dog4 = Dog("example","example","example",1)
val dog5 = Dog("example","example","example",1)
//... goes on...
}
Could you suggest me an efficient way? Thanks in advance.
CodePudding user response:
As a beginner, don't even worry about trying to optimize this. Just use a FOR loop or initialize the array manually and it'll be fine. If you want to access it in different Activities
, just make the ArrayList
a global variable by declaring it outside of one of your classes. In your case, this means declaring it above MainActivity
.
The better but more involved way to do it is to store all these items in a pre-populated database. That way, you're not creating an ArrayList
every time the app runs, you're not taking up memory unnecessarily, and you're only accessing what you need at any given time.