hi geys ,

I need ow to return a array string to my method

   public String[] SearchPort(){
        ArrayList<String> arr=new ArrayList<>();


        Win32Driver w32Driver= new Win32Driver();

        w32Driver.initialize();


        port= CommPortIdentifier.getPortIdentifiers();

        while(port.hasMoreElements()){


       cuport=(CommPortIdentifier) port.nextElement();



        if(cuport.getPortType()==CommPortIdentifier.PORT_SERIAL){


         //  return cuport.getName();

            arr.add(cuport.getName());



                String[] t=new String[arr.size()];


            t=arr.toArray(t);

          for(String j:t){



         return t;


          }






        }

        //System.out.println(cuport.getName());  
        }

 String h[]={"noo data "};
 return h;
    }


    and this is the main  code 




 SendRecPort sd=new SendRecPort();

                    String[] result = sd.SearchPort();
    for (int i=0; i<result.length; i++) {

  jComboBox1.addItem(result[i]);
         // jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(result[i]));
    }  

always retunr one value from search() methode

Recommended Answers

All 2 Replies

thanks I slove the problem

but any Idde for optimize the code of the method search() ????????

well, this code looks very fishy to me:

String[] t=new String[arr.size()];
            t=arr.toArray(t);
          for(String j:t){
         return t;
          }
  1. declare your t array outside of the loop, don't create a new instance each iteration, just overwrite the existing one:

    String[] t;

    while ( condition ){
    // ...
    t = new String[arr.size()];
    // ...
    }

or, better yet:

String[] t;
while ( condition ){
  // ...
  t = arr.toArray(t);

Second remark... do you understand why this:

for ( String j : t ){
  return t;
}

is just a waste of code?

if ( t.size() > 0 ){
  return t;
}

should do just fine.

but at this point, you are doing quite a lot within your loop, which I think you don't want in your loop. after all, transforming your arrayList, let alone returning the values, shouldn't happen untill all the values are found (if I understand your code correctly, anyway). so, basically:

ArrayList<String> arr = new ArrayList<String>();

while( condition ){ // the hasMoreElements
  arr.add(new Element);
  // additional code
} // end of while loop.

if ( arr.size() == 0){
  return {"no data found"}; // even though I would op to either return null,
  // an empty array or throw an Exception at this point,depending on the
  // situation.
}
// now we know there are elements, so we can safely create our array:
return arr.toArray(new String[arr.size()]); 

your code itself isn't that bad, but it's the logic that might need some work here and there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.