• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Picking a random element from an arrayList

 
Greenhorn
Posts: 26
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi folks! How're you all doing? I have a simple question: how can I choose a random element from an arrayList? This is what i wrote:



When working with normal arrays I use to generate a random number using Math.random() (which choice interval depends from the length of the array itself), and print out the array element which index is equal to the random number. But here it doesn't seem to work.

Can you help me?
 
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, but your query is not clear.  You wish to select something from the list but your codes seems to be adding something to the list.
 
Saloon Keeper
Posts: 15484
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nik Recort wrote:But here it doesn't seem to work.


Why not? What happens?

Indexing is the same in lists and arrays, you just call the get() method instead of using the array's indexer.
 
Marshal
Posts: 8856
637
Mac OS X VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nik Recort wrote:But here it doesn't seem to work.


To define how many elements List has, it can be checked with its method size() as oppose to length in case of arrays - maybe you were mistaken in this area?
 
Rancher
Posts: 89
13
Scala Eclipse IDE MySQL Database Tomcat Server Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So a couple of things to nitpick about you program. Your formatting could use some work, such as making the ending brace of the main method line up with the beginning as well as having uniform indentation on the statements. Also, you are created new string empty string objects, which is generally something you shouldn't do as strings have their own special place in the heap and creating them this way stores them outside that area. What are these string objects purpose?

-Zach
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
More specific nitpicks:

Nitpick #1

Instead of this:
do this:
Rationale:
1. Prefer to use the interface type (List) instead of the concrete implementation type (ArrayList) when declaring variables
2. Variable names should start with a lowercase letter
3. Use the diamond operator and type inference to reduce redundancy in your code on the right hand side (RHS) of the assignment statement.

Nitpick #2

Instead of this:
do this:
Rationale:
1. Do not create new instances of String if you really mean to use a String literal.
2. Variable names start with a lowercase letter
3. Make your variable names meaningful to other people. Ikkyo is the first technique -- people who don't practice Aikido should be able to get that from your code.

(Yes, I study Aikido)
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Additionally, prefer using java.util.Random instead of Math.random(). Code that uses Random is cleaner and clearer and there are more methods that allow you to generate different kinds of random values like int, long, boolean, byte, double, float so you don't have to do explicit type casting.



       
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Finally, you can use the java.util.Arrays class to conveniently create a List:
 
Zach Rode
Rancher
Posts: 89
13
Scala Eclipse IDE MySQL Database Tomcat Server Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:Finally, you can use the java.util.Arrays class to conveniently create a List:



If I remember right this creates a List object and not an ArrayList which he was looking for. You can change it to an ArrayList by wrapping it in a constructor though

 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zach Rode wrote:If I remember right this creates a List object and not an ArrayList which he was looking for. You can change it to an ArrayList by wrapping it in a constructor though



If you declare your variable using the interface type (java.util.List), then it doesn't matter what the implementation class is. Wrapping the object returned by Arrays.asList() like that defeats the purpose of using Arrays.asList() in the first place, which is to get some kind of List implementation that contains as elements all the things you pass as arguments.  The actual type of the List implementation should not matter.

See Prefer programming to interfaces, not implementations
 
Zach Rode
Rancher
Posts: 89
13
Scala Eclipse IDE MySQL Database Tomcat Server Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
that fair if Nik only wants to use the methods associated with list, but the original code snippet is set as an ArrayList, so he might want to change the size of the list dynamically or use be able to make statements involving the index (List does implement use of indexes so this is invalid). Implementation type could matter also if ArrayList overrides List methods.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zach Rode wrote:Implementation type could matter also if ArrayList overrides List methods.


No, it really doesn't.

List has an add() method. ArrayList implements List.

Remember, List is an interface type, not a class type.

See Liskov Substitution Principle.  

And I suspect that @OP wrote what he originally wrote out of inexperience, not so much intent.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Liutauras pointed out to me that @Zach was saying that OP meant to have a list that could be added to. I was fixated on LSP and programming to interfaces and totally overlooked the fact that the List that Arrays.asList() returns is fixed-length.

My mistake, Zach, you were right in pointing out that aspect of what OP wanted to do.  

In that case, I'd extract to helper method like this:


This way, you're still hiding the implementation detail that you're using an ArrayList while keeping the high-level code programmed to the List interface.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think it's worth pointing out some nuances with this formulation:

It's easy, or at least conceivable, to see how passing the result of Arrays.asList() to the ArrayList() copy constructor like that might look redundant to the unsuspecting or, as in my case, clueless reader. Admittedly, my intuition about what Arrays.asList() does was wrong; I thought it returned an expandable List implementation, which apparently it doesn't.

That brings us to the Principle of Least Astonishment/Surprise (POLA). My response was to refactor to use a private method listFrom(...). That might be a bit much though if it's only used in one place. I think an equally valid way to address the potential for surprise is to add a comment that explains why you're doing something, just to avoid being misunderstood:


Also, the comment below was what I originally wrote but it sounded too much like it was explaining what was happening instead of why it was written that way.

It's a small change but one that makes quite a big difference in the way the comment comes across. Why vs. What.
 
Zach Rode
Rancher
Posts: 89
13
Scala Eclipse IDE MySQL Database Tomcat Server Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I appreciate you reexamining it. I ran into the issue of a non-expandable list several times doing CodeWars, so its habit to transform all Arrays.asList() calls to expandable ones. I do think I forgot to add the type identifier( <> what are these things called again?)  when I said new ArrayList



-Zach
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zach Rode wrote:<> what are these things called again?


It's called the diamond operator
 
Bartender
Posts: 5465
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Indeed, for ArrayLists you have the method 'removeRange', that ia not available for a List. Likewise, a TreeSet has a very useful method 'ceiling' (and 'floor'), that is not in a Set. There may be more of those, but these are the ones I encountered so far.

But list.get(random) should be fine  
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Piet Souris wrote:Indeed, for ArrayLists you have the method 'removeRange', that ia not available for a List. Likewise, a TreeSet has a very useful method 'ceiling' (and 'floor'), that is not in a Set. There may be more of those, but these are the ones I encountered so far.


Note that removeRange() is protected.  TreeSet.ceiling() and floor() are from NavigableSet.

I would be very surprised if there are any public methods in an implementation class that does not override a method specified by an interface it implements. To me, that would be a design smell since client code must be written to the implementation, not the abstraction.
 
Nik Recort
Greenhorn
Posts: 26
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As I said my goal was to print a random element from the arrayList, in this case one of the two elements present (I know, maybe they are too few). I have studied so far that if you want a container that automatically accepts new elements without worrying about setting its size, arrayList is ideal.

I have tried this, which worked for normal arrays (I have corrected and tried it again to be sure before posting, I have also removed the capital letter from "techniques):



But I get errors in line 19 and 20.

And, by the way, what is the error in assigning an element of the array to a <String>? Aren't <String>'s, in this case, elements of the arrayList?

Oh, and in this case I want to use an ArrayList to play a bit with it, and get used to it. You know, I still need to write a looooot of programs to get used to it =).
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nik Recort wrote: I have also removed the capital letter from "techniques):


Please carefully read through all the feedback given before. That is only one small thing. There are many more things you need to do to fix your code.

Also, try to see the output given by these two snippets of code.

Understand why you get the output and you will be closer to understanding why you're not getting what you expect.
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
TIP: Use the Preview button before posting a message so you can see the line numbers in the code that you post inside code tags. Then you can reference the correct line numbers.

You wrote:I get errors in line 19 and 20


... actually, lines 11 and 12 in the code you posted.

You wrote techniques.size instead of techniques.size().

And again, you might want to use java.util.Random instead of Math.random(). The code is much clearer when you use Random.
 
Nik Recort
Greenhorn
Posts: 26
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:TIP: Use the Preview button before posting a message so you can see the line numbers in the code that you post inside code tags. Then you can reference the correct line numbers.

You wrote:I get errors in line 19 and 20


... actually, lines 11 and 12 in the code you posted.

You wrote techniques.size instead of techniques.size().

And again, you might want to use java.util.Random instead of Math.random(). The code is much clearer when you use Random.



You are right. I was mistaken again. And I wrote line 19 and 20 because I deleted the comment lines above the program before posting it, without checking properly before hitting that post button. Thanks for letting me notice.

I am a bit lost, this is what I think you told me to add:


Now it gives me errors at lines 7 and 15.

Is it still convenient to add this line?
Sorry if I sound repetitive, but I don't have much of a grasp on Java, yet.
 
Zach Rode
Rancher
Posts: 89
13
Scala Eclipse IDE MySQL Database Tomcat Server Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Nik,

This has certainly been a lengthy conversation. So your line numbers might be skewed again but I think you're getting an error on this line


and its because you create the Random object but you don't do anything with it. You're actually saying object * int = int. try looking at this page and see which method might return an int like you want.

As far as the ArrayList conversation goes, the single line you quoted can go in place of line 3 in your code and you can remove lines 4-9.

-Zach
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Nik Recort wrote:Is it still convenient to add this line?


Yes, it is. There's really no point in these lines since you use those variables only one time:


 
Marshal
Posts: 79151
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:. . . . There's really no point in these lines since you use those variables only one time: . . .

. . . but this is quicker to write:-
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:. . . but this is quicker to write:-


Yeah, it gets a little noisy as you add more items though.

Looking around, I found this article that lists many different options: https://memorynotfound.com/initialization-arraylist-one-line-example/

I kind of like the last way:

Very interesting one that uses an instance initialization block and anonymous class:

Lots of ways to skin this cat. Or beat this dead horse.
   
 
Stephan van Hulst
Saloon Keeper
Posts: 15484
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or in Java 9:

Or if it needs to be modifiable:
 
Nik Recort
Greenhorn
Posts: 26
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok folks, thank you all very much for your time. I'll dig deeper into it, and in case return to it later when I know more, if I cannot make it work now.
 
Bartender
Posts: 1868
81
Android IntelliJ IDE MySQL Database Chrome Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Mooo!

Your posting was just mentioned in the June 2018 CodeRanch Journal and for that you get a cow.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic