用ArrayList替换数组

时间:2013-07-28 02:53:36

标签: java xml

我正在尝试用arraylists替换我拥有的数组,所以我不必担心管理数组并且可以清理我的代码。我刚刚自学了arraylists所以我有一些问题。主要是在这些所有“集合”和“获取”的类中。我不认为我有正确的语法,因为我得到一个ArrayList / String冲突错误。基本上试图得到:

public static ArrayList<Resource> importResourcesFromXML(String documentLocation)

从XML文档导入资源的arraylist。我还想将Resources和我的T_Resources中的数组转换为arraylists。这是我到目前为止的代码,我相信我已经正确地实现了资源,但可以使用其他两个帮助正确显示XML资源。

编辑:我想尽可能完全消除数组并用arraylist替换它。我想尝试避免将数组转换为arraylist。

import java.util.ArrayList;


public class Resources {

//private static final int  MAX_SUBJECTS = 20;
private String              title;  
private String              description;
private Identifier          identifier;
ArrayList<Subject> subject = new ArrayList<Subject>();
//private int               subjectCount;


public Resources() {

    title           = "unknown title";
    description     = "unknown description";
    identifier      = null;

    //subjects      = new Subject[MAX_SUBJECTS];
    //subjectCount  = 0;

}

public void setTitle(String newTitle) {

    title = newTitle;

}

public String getTitle() {

    return title;

}

public void setDescription(String newDescription) {

    description = newDescription;

}

public String getDescription() {

    return description;

}

public void setIdentifier(Identifier newIdentifier) {

    identifier = newIdentifier;

}

public Identifier getIdentifier() {

    return identifier;

}

public void addSubject(Subject newSubject) {

    subject.add(newSubject);

}

public ArrayList<Subject> getSubjects() {

    //Subject[] result = new Subject[subjectCount];


    //System.arraycopy(subjects, 0, result, 0, subjectCount);

    return subject;
}

}

public class ResourceImporter {

// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {

    // The XML document.
    //
    Document documentIn     = null;

    // The parser that reads in an XML files.
    //
    DocumentBuilder parser  = null;

    // Pull the document
    //
    try {

        // Obtain a document parser.
        //
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        builderFactory.setNamespaceAware(true);

        parser = builderFactory.newDocumentBuilder();

        documentIn = parser.parse(documentLocation);

    } catch (ParserConfigurationException p) {

        System.out.println("Error creating parser.");
        System.out.println("   " + p.getMessage());

    } catch (SAXException s) {

        System.out.println("Document is not well formed.");
        System.out.println("   " + s.getMessage());

    } catch (IOException i) {

        System.out.println("Error accessing the file.");
        System.out.println("   " + i.getMessage());

    } catch (Exception e) {

        System.out.println("Unknown error occurred.");
        System.out.println("   " + e.getMessage());

    }


    return documentIn;

}

public static ArrayList<Resource> importResourcesFromXML(String documentLocation) { 

    ArrayList<Resource> resource = new ArrayList<Resource>();

    Document doc;

    Element resourceElement;

    Element titleElement;
    String title;

    Element descriptionElement;
    String description;

    Element identifierElement;
    String identifiers;

    Element urlElement;
    String url;

    NodeList subjectList;

    Element subjectElement;
    String subjects;

    Element categoryElement;
    String category;

    Element subcategoryElement;
    String subcategory;


    doc = loadXMLDocument(documentLocation);

    resourceElement = (Element)doc.getElementsByTagName("resource").item(0);


    if (resourceElement != null) {

        titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);  

        resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );

        descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);

        resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );

        identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);


        if (identifierElement != null) {

            Identifier identifier = new Identifier();

            urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);

            identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );

            resource.setIdentifier(identifier);

            subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);

            if (subjectElement != null) {

                subjectList = subjectElement.getElementsByTagName("subject");

                for (int i=0; i < subjectList.getLength(); ++i) {

                    Subject subject = new Subject();

                    subjectElement = (Element)subjectList.item(i);

                    categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);

                    subject.setCategory( categoryElement == null ? "unknown"  : categoryElement.getTextContent() );

                    subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);

                    subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );

                    resource.addSubject(subject);

                }
            }

        }
    }

    return resource;

}

}

import java.util.ArrayList;


public class T_Resources {

public static void main(String[] args) {

    ArrayList<Resource> resource = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");

    displayResources(resource);

}

private static void displayResources(ArrayList<Resource> resource) {

    ArrayList<Subject> subjects;

    System.out.println(resource.getTitle());

    System.out.println(resource.getDescription());

    System.out.println(resource.getIdentifier().getURL());

    subjects = resource.getSubjects();

    for (int i=0; i < subjects.size(); ++i) {

        System.out.println(subjects.getCategory() + " :: " + subjects.getSubcategory());

    }

    System.out.println();
}

}

public class Subject {

private String category;
private String subcategory;

public Subject() {

    String category         = "unknown";
    String subcategory      = "unknown";

}

public Subject(Subject subject) {

    category        = subject.category;
    subcategory     = subject.subcategory;

}

public void setCategory(String newCategory) {

    category = (newCategory == null) ? "unknown" : newCategory;

}

public String getCategory() {

    return category;

}

public void setSubcategory(String newSubcategory) {

    subcategory = newSubcategory;

}

public String getSubcategory() {

    return subcategory;

}
}

public class Identifier {

private String url;

public Identifier() {

    url = "unknown";

}

public void setURL(String newURL) {

    url = newURL;

}

public String getURL() {

    return url;

}

}

1 个答案:

答案 0 :(得分:3)

如果我误解了一些内容,请告诉我,但是如果您正在寻找的是将原始数组转换为ArrayList的方法,那么我将使用以下内容:

arrayList = Arrays.asList(array);