Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ClassCastException: java.lang.String cannot be cast to Ljava.lang.String

I get this error->

java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String; 

From the code pasted below.

public class LoginAttemps extends Setup {
    public void testSearchCountry() throws Exception {
        driver.get("http://www.wikipedia.org/wiki/Main_Page");
        ReadExcelDemo readXls = new ReadExcelDemo();
         List dataList = readXls.getData();
         for (int i = 1; i < dataList.size(); i++) {
             String[] testCase = new String[5];
             String[] test = (String[]) dataList.get(i);
             String countryName = test[0];
             String countryDesc = test[1];
             driver.findElement(By.id("searchInput")).clear();
             driver.findElement(By.id("searchInput")).sendKeys(countryName);
             driver.findElement(By.id("searchButton")).click();
             String str = driver.findElement(
             By.xpath("//h1[@id='firstHeading']/span")).getText();
             System.out.println(countryDesc);
             Assert.assertTrue(str.contains(countryName));
         }
   }
}

I think the issue is with String[] test = (String[]) dataList.get(i);

But I am not sure about resolving this exception.. Any clues?

like image 865
Shari Avatar asked Mar 24 '15 11:03

Shari


People also ask

How do I resolve Java Lang ClassCastException error?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.

What is class Ljava Lang String?

It's just what the toString method of a JVM array returns. The default implementation of toString that gets inherited from java.lang.Object is more or less equal to this: def toString(): String = this.getClass.getName + "@" + this.hashCode.toHexString. The class name of a String array is [Ljava. lang. String; .

What is ClassCastException in Java?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.


1 Answers

You can not cast "String" into "Array of Strings".

You can only put a string into a slot within an array.

What you can do is:

    String theString = "whatever";
    String[] myStrings = { theString };
like image 127
GhostCat Avatar answered Sep 27 '22 18:09

GhostCat