Note that there are some explanatory texts on larger screens.

plurals
  1. POElegant way of specifying either objects or enums as a parameter
    primarykey
    data
    text
    <p>I've made the following code to turn an <code>ArrayList</code> (say values <code>"Cat", "Dog", "Fish"</code>) into a human-readable string (say <code>"Cat,Dog,Fish"</code>), which is a simple task but I want to extend it elegantly. What I've got so far is:</p> <pre><code>public static String makeStringList(Iterable&lt;String&gt; items) { StringBuilder sb = new StringBuilder(); for (String item : items) { sb.append(item); sb.append(","); } if (sb.length() &gt; 0) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } </code></pre> <p>But I have another object which is an <code>ArrayList</code> of <code>Enum</code> values, say:</p> <pre><code>enum Animal { cat("Cat"), dog("Dog"), fish("Fish"); String value; Animal(String num) { value = num; } } </code></pre> <p>And an <code>ArrayList&lt;Animal&gt;</code> containing <code>(Animal.cat, Animal.dog, Animal.fish)</code>.</p> <p>What's the best way to extend my <code>makeStringList</code> function so that it accepts <code>ArrayList</code>s of either <code>Enum</code>s or <code>String</code>s? I've tried changing the parameter to <code>Iterable&lt;Object&gt; items</code> and using <code>toString()</code> but apparently my enums don't extend <code>Object</code> so there's no <code>toString()</code>. I've also tried creating an interface <code>hasStringRepresentation</code> with a function <code>getStringRepresentation</code>, which works great but won't work for strings.</p> <p>Is there an elegant way I can extend the makeStringList function to accept either Objects or Enums? The obvious answer is overloading makeStringList but I'd like to limit the question to answers which don't involve overloading.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload