Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

my for loop is rather long - java

Tags:

java

My for loop is too long. As demo there is three for loops going on for methodB. Is there a way I could reduce this to a short for loop (one for loop)? Thanks

    public class MyMates  
    {

       private static TreeSet<String> myTable = new TreeSet<String>();

       private static String[] names1 = null;
       private static String[] names2 = null;
       private static String[] names3 = null;


       public MyMates()
       {
        super();
        myTable = new TreeSet<String>();
       }


       public  static String methodA(String aTemp)
       {
         String[] names1 = new String[] {"Amy", "Jose", "Jeremy", "Alice", "Patrick"};
         String[] names2 = new String[] { "Alan", "Amy", "Jeremy", "Helen", "Alexi"};
         String[] names3 = new String[] { "Adel", "Aaron", "Amy", "James", "Alice" };

         return aTemp;
      } 



    public static String methodB(String bTemp)
     {

        for (int i = 0; i < names1.length; i++) {
        myTable.add(names1[i]);
        }
        System.out.println(myTable);

        for (int i = 0; i < names2.length; i++) {
        myTable.add(names2[i]);
        }
        System.out.println(myTable);

       for (int i = 0; i < names3.length; i++) {
       myTable.add(names3[i]);
       }
       System.out.println(myTable);

    return bTemp;
   }

enter code here

like image 582
DiscoDude Avatar asked Mar 11 '26 03:03

DiscoDude


2 Answers

Actually, you don't need any for loop:

myTable.addAll(Arrays.asList(names1));
myTable.addAll(Arrays.asList(names2));
myTable.addAll(Arrays.asList(names3));
like image 76
Maurice Perry Avatar answered Mar 12 '26 17:03

Maurice Perry


On extract method refactoring

When you have something like this (in pseudocode):

doA(x);
doB(x);
doC(x);

doA(y);
doB(y);
doC(y);

You can often (though not always) extract doA/doB/doC and refactor into a method doABC like this:

void doABC(o) {
  doA(o);
  doB(o);
  doC(o);
}

Then elsewhere you do:

doABC(x);
doABC(y);

This is called extract method refactoring.


On for-each loop

Since 1.5, the for-each loop is added for arrays and instances of Iterable. Here's a simple example:

    String[] names = { "Alice", "Bob", "Carol" };
    for (String name : names) {
        System.out.println(name);
    }
    // "Alice", "Bob", "Carol"

A quote from Effective Java 2nd Edition, Item 46: Prefer for-each loops to traditional for loops:

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as "in." Thus, the loop above reads as "for each element e in elements." Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once.

The for-each loop is not applicable to all cases, but when it does, you should always try to use it to improve readability and minimize chances of errors.

See also

  • Java Language Guide/foreach loop

On Collection.addAll

Collection<E> defines addAll(Collection<? extends E> that can be used to add all elements from one Collection to another (assuming it's typesafe).

Moreover, there's Arrays.asList(T...) that can create a List backed by an array of references (not primitives!).

This means that in this case you can do:

myTable.addAll(Arrays.asList(names1));
myTable.addAll(Arrays.asList(names2));
myTable.addAll(Arrays.asList(names3));

Note that a common pitfall is to pass, e.g. an int[] to Arrays.asList, and hoping to get a List<Integer>. This doesn't work, because while an int is autoboxable to an Integer, an int[] is NOT autoboxable to an Integer[].

Related questions

  • Arrays.contains(int) error
  • Arrays.asList() not working as it should?
  • Java noob: generics over objects only?

On local variables

You've written the following:

public class MyMates  {
   private static String[] names1 = null;
   private static String[] names2 = null;
   private static String[] names3 = null;

   public  static String methodA(String aTemp) {
     String[] names1 = ...;
     String[] names2 = ...;
     String[] names3 = ...;

     return aTemp;
   }

It needs to be said that the assignments in methodA are to locally declared variables names1, names2, names3 that shadows the fields with the same names. These variables goes out of scope at the end of methodA, and thus serve little to no purpose.

More often than not this is not what you want. You probably intent to assign to the fields instead, i.e.:

   public  static String methodA(String aTemp) {
     names1 = ...;
     names2 = ...;
     names3 = ...;

     return aTemp;
   }
like image 32
polygenelubricants Avatar answered Mar 12 '26 16:03

polygenelubricants



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!