"final" parameter in a constructor

I saw a code like this.
class Example {
class Test {
public Test(final Example example) {
What does that mean to have a final type parameter in a constructor?
Does that mean that I don't need a "Example" class variable to use the object that are passed to a parameter?
Could you just explain the meaning of "final" variables/parameter?
Thanks

The final keyword means that once a value has been assigned to a variable it cannot be changed. Same goes for parameters.
final int x = 42;
x = 600; // error
public void someMethod(final int x) {
    x = 600; // error
}

Similar Messages

  • Why "System.setIn()" can set the final parameter "System.in"?

    When i worte a class to test the System class,I have read the System class source.
    I found that the parameter System.in is defined as a final parameter.
    But strangely, why the System.setIn() can change the System.in?
    This is the fragment of the source
    public static void setIn(InputStream in) {
         setIn0(in);
    private static native void setIn0(InputStream in);the setIn() method calls a private method called setIn0(), but the setIn0() does noting. I found a "native" definition? I think this is the key reason
    Pleas tell me what the "native" means and the how the setIn() & setIn0() method work?

    You really can't set final variables after they've been set in Java code, but Sun gets away with it by using native (that is non-java) code. It's a (necessary?) evil and should not be taken as a guide to good code. Just imagine a big "Big Bad Voodoo" sign above the native method.

  • Extending parameter type in constructor declaration?

    I've come across a couple of places where I really want to have the compiler use a specific implementation for types of generic parms. As things stand now, I write two classes: one that defines a general mechanism, and one (may or may not be derived from the first) that provides a more specific mechanism.
    I know that this isn't possible given the generic type erasure, but I thought I came up with a way to make it work. Of course, this doesn't work either, but I wanted to know what potential misuse causes this syntax to be rejected by the spec.
    public class TNum<T> {
        private T value;
        public TNum(T value) { this.value = value; }
        public <N extends Number & T> TNum(N value) { // compiler rejects this in either order
            this(value);
    }So far, the two cases that I'd use this type of technique:
    1) Comparison functors -- there are two choices generally
    class Less<T> {
        public Less(Comparator<T> comp) {...}
    class Less<T extends Comparable) {
        public Less() {}
    }I could eliminate a class if I could write
    class Less<T>{
        public <T> Less(Comparator<T> comp) { ... }
        public <C extends Comparable & T>Less() {
            this(new ComparableComparator<C>());
    }2) Swing Editors & Renderers: the basic implementation is the same for all parm types, but there are a couple of minor extensions when dealing with Numbers.
    David Hall
    http://jga.sf.net

    I'm not sure about the multiple-inheritance argument:
    there are a number of places where the inferencer is
    working with an empty set of potential classes. For
    example <? extends String>: String being final can't
    possibly have a derived class.
    Given <N extends Number & T>, I would expect due to
    the type erasure rules that the type N would be erased
    to Number for actual class file generation.Granted, but then the problem is the compiler doesn't know what T is here. If T turned out to be (pick any class) "Thread" then you've written N extends Number & Thread, which clearly doesn't work.
    Whether this is the actual problem in this case or not I don't know, but I don't see to allow you to write 'N extends X & Y' unless the compiler could know at least one of X and Y is an interface. Given you have no bounds on T in your example this is impossible.
    ComparableComparator
    I've seen it in a number of libraries in addition to
    JGA and no one has a better name for it. It is an
    attempt to have one visible method of comparing
    objects instead of two.Oh, I see, you're trying to do pattern matching:
    class ComparableComparator<U extends Comparable<U>> implements Comparator<U> {
        public int compare(U x, U y) {
            return x.compareTo(y);
    class Less<T> {
        public Less(Comparator<T> comp) {
        public Less() {
            this(new ComparableComparator<T>());
    BoundToWork.java [33:1] type parameter T is not within its bound
            this(new ComparableComparator<T>());
                                          ^
    1 error
    Errors compiling BoundToWork.This won't compile because T is not bound so the compiler can't know T implements Comparable<T>.
    One could write:
    class Less<T extends Comparable<T>> {
        public Less(Comparator<T> comp) {
        public Less() {
            this(new ComparableComparator<T>());
    }Which compiles but defeats the whole object of what you're trying to do...
    The thing is, I don't understand how you're planning to use this, do you have in mind something like this?
        class NotComp {} //doesn't implement Comparable<NotComp >
        Less<NotComp > l1 = new Less<NotComp>(new NotCompComparator());
        class Comp implements Comparable<Comp> { ...}
        Less<Comp> l2 = new Less<Comp>();Are you essentially trying to say that the no-arg constructor should only be available if the type of the parameter T happens to extend Comparable<T>, and conversely if T is not Comparable<T> then one must use the one-arg constructor of less and explicitly supply a Comparator object?
    If I've understood you correctly then I can't see how this can work. You're basically trying to constrain which constructors are available based on the interfaces implemented by the type parameter (T) in Less<T>. But that can't work... both constructors must be callable for all instantiations of Less<T> ?
    Please forgive me if I've gone off on a total tangent and misunderstood your intent.

  • Final class and private constructor

    Whats the difference in a final class and a class with private constructot?
    If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)

    You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
    KajThat depends on the signature of the private constructor.
    If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
    If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
    class Private1 {
         private int q;
         private Private1() {
         public Private1(int i) {
              q = i;
         public void print() {
              System.out.println(q);
    public class Public1 extends Private1 {
         public Public1() {
              super(1);
         public static void main(String[] args) {
              new Public1().print();
    }for example compiles and runs perfectly.
    But remove the call "super(1);" from the constructor and it will fail to compile.

  • How to generate "constructor" for parameter object

    Hello,
    As part of my research project I need to find the "constructor" of a given
    parameter object.
    For example: Suppose we have the following method -
    public void int pop(Stack st) {
    //some code...
    I want to generate code that calls this method and its parameter with its
    constructor. Like -
    pop(new Stack(10));
    As you can see I need to return a valid instance of the parameter to the
    method (null wont do).
    I dont know what library or API to use for this purpose.
    Your help is highly appreciated.
    Thanks,
    Fayezin

    That's not a great example. If you have a Stack class, then pop() should be a method on that class, not some other class. And if you created a new Stack object, then presumably it would be empty, so popping it should cause an exception.
    Anyway, if you want to get the constructor of a class, use Introspection. There may be a better solution though, depending on what you're actually trying to accomplish.

  • GetParent() not working in constructor

    ok Im trying to make these two classes that extend JPanel. The first one has a Container added to it and basically just displays the currently selected container. The second one is under it and will display information about the container. In the construction of the second one, I need to access the getCurrentContainer() function of the parent frame. However, getParent() doesnt work and it seems like a pain to put it as a parameter in the constructor. Has anyone found a way around this?

    However, getParent() doesnt work and it seems like a
    a pain to put it as a parameter in the constructor.Why so? My move would be to create a Panel which will be able to display info about any given Frame.
    // Pseudocode
    public FrameInfoPanel extends JPanel {
      protected Frame model;
      public FrameInfoPanel(Frame aModel, ...) {
        super(...);
        model = aModel;
        new FrameInfoPanel(someFrameMaybeParentOne, ...);Denis Krukovsky
    http://dotuseful.sourceforge.net/

  • How to hanlde a parameter in CodeDomSerializer' CodeVariableDeclarationStatement

    We want to use "CodeDomSerializer" and
    during Serialize process to replace
    Dim UltraTab1
    As xxx.Tools.Windows.TabObject
    = CType(New
    Infragistics.Win.UltraWinTabControl.UltraTab(), xxx.Tools.Windows.TabObject)
    with       
    Dim UltraTab1
    As xxx.Tools.Windows.TabObject
    = New xxx.Tools.Windows.TabObject()
    We have achieved our goal in thread:
    http://social.msdn.microsoft.com/Forums/en-US/265765f6-1b07-4508-8450-5a5fc2544926/vbnet-how-to-handle-runtime-error-unable-to-cast-object-of-type?forum=Offtopic&prof=required
    However, there is one case, we do not know how to handle it.
    This is a special case which TabObject pass a parameter into its constructor:
    When we open the form in designer and add a new tab into a form. We see the following code
     Dim UltraTab2 As xxx.Tools.Windows.TabObject = New xxx.Tools.Windows.TabObject(True)
    Change to: Dim UltraTab2 As Xxx.Tools.Windows.TabObject = New Xxx.Tools.Windows.TabObject().
    Boolean parameter is disappeared.
    How can we use “CodeDomSerializer’ CodeVariableDeclarationStatement” to detect there is parameter and keep the patameter during replacement.
    So we can replace following:
    Dim UltraTab2 As xxx.Tools.Windows.TabObject = CType(New Infragistics.Win.UltraWinTabControl.UltraTab(True), xxx.Tools.Windows.TabObject)
    With
    Dim UltraTab2 As xxx.Tools.Windows.TabObject = New xxx.Tools.Windows.TabObject(True)
    Thx!
    JaneC

    Hi,
    I am afraid that this is not supported here, since this issue is mainly related to the structure of a control which blongs to third-party and its publisher has its website in which you could post this issue to get support.
    Thanks for your understanding.
    Regards.
    Hi
    Dave Patrick,
    This issue is mainly related to a control blongs to third-party which is obviously
    beyond the scope of our support, hope you will not move it back again. : )
    Regards.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Overloading constructor of a child that inherits from a class that inherits from Windows.Forms

    The title might be a bit confusing so here is the layout.
    - classHForm inherits System.Windows.Forms.Form
    - frmDoStuff inherits classHForm  (written by someone else and used in several applications)
      - does not have a constructor specifically defined, so I added the following thinking it would override the parent
    Sub Public New()
    End Sub
    Sub Public New(byval data as string)
    'do stuff
    End Sub
    In my code, I want to instantiate frmDoStuff, but I need to overload it's constructor and populate fields within this form. The problem I'm running into is that when I run this, it is using the constructor from classHForm and ignores any constructor in frmDoStuff.
    I guess you can't override the parent constructor? Is that why it won't work?
    I didn't want to overload the classHForm constructor, but I will if that's the way to go.
    my code:
    dim frm as new frmDoStuff(myString)
    Note: I would love to show actual code, but not allowed. Against company rules.

    Your code is similar. The value I pass into frmDoStuff is supposed to set a value for a textfield.
    Public Class frmDoStuff
    Inherits classHForm
    Public Sub New(ByVal s As String, ByVal gridData() as String)
    txtMyTextField.text = s LoadGrid(gridData)
    End Sub
    I also have a datagridview I need to populate in frmDoStuff and thought I would have another string or string array as a second parameter to the constructor and then call a routine from the constructor to populate the datagrid.
    of course, when I run it this way, the code is not being reached. I'll build an example as COR suggested and maybe someone will see where I'm going wrong.
    [UPDATE]
    I created a simple example and it worked. So, now I need to try to understand what is different in the actual code.
    Here is my example:
    Parent Class inherits form
    Imports System.Windows.Forms
    Public Class classMyForm
    Inherits System.Windows.Forms.Form
    Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    End Class
    Public Class frmDoStuff
    Inherits classMyForm
    Public Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    End Sub
    Public Sub New(ByVal sStuff As String)
    MyBase.New()
    InitializeComponent()
    'Populate the textbox
    TextBox1.Text = sStuff
    End Sub
    End Class
    Public Class frmMyForm
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim frm As New frmDoStuff(TextBox1.Text)
    frm.Show()
    End Sub
    End Class
    Just to recap. The actual parent was created a few years ago and the child form that I'm calling, "frmDoStuff" was created a couple years back and is used in several applications. I need to use it in my application, but I need to populate a couple
    controls when the form is loaded. As you can see in this example, I successfully overloaded the constructor to populate the textbox in frmDoStuff.
    In my real life situation, my overloaded constructor seems to be getting ignored when i step through the code. I'll go back and do some more testing.

  • Instantiate a Class through a constructor argument of another class.

    public function LevelManager(owner:Home)
                                  _owner = owner;
    In my LevelManager Class I have the above code in the constructor. Home is another Class which is not instantiated anywhere with the new keyword. It is merely a parameter in the constructor and then passed into the body and assigned to a local variable. I didn't know you could instantiate a class through a function parameter. Is that right???
    Cheers in advance.

    Well, I know Amy is big on design patterns and she is going to slap me but I am the guy who is not a big fun of DPs in regular Flash applications. I have many reasons to dislike them.
    I am not against DPs in principal. In collaborative environments (big teams) or in situations when software is developed for industrial consumption or as partially closed frameworks - it makes sense. Otherwise - they are just possible solutions and reference point at best. In Flash they frequently are major silly overkills. They are more of academic than practical value contrary to what people tend to believe.
    Design patterns are possible solutions that developers came up with heuristically base on the problems they needed to solve - not vice versa. Problems do not dictate design patterns.
    There is a strong tendency among DPs proponents and followers to make DPs self-fulfilling prophecies. Instead of conceptualizing of particular application needs developers often are searching for DP first and then try to squeeze logic into a particular or a group of several design patterns.
    If a person is taught that DPs is the only way to go - there is a great danger of killing creativity and the thought process.
    I strongly believe that what makes a star programmer is the ability to conceptualize the project, model it well and only then find coding solutions based on language capacities. And to question any suggestions in favor of current task efficiencies.
    By the same token, if your painting doesn't need color red - why use it? This is another thing that happens often - developers implement something that is actually not needed.
    Code is cheap! When project is well conceived and modeled - coding takes very little time. One ends up with his/her own "design pattern" that may or may not fall into one of DPs that is articulated already.
    Also, there is a great deal of activism around DPs that, as with any activism, forms an ideology that is full of misleading simplifications.
    First one is that OOP is equated to DPs usage. This is totally dangerously  untrue!!!
    Another one is you mentioned. Spaghetti coding is not the only alternative to design patterns. In other words, if one doesn't use DP - it absolutely doesn't mean person is engaged in spaghetti coding. And vice versa - DP does not shield program from spaghetti coding. I have seen DP warriors going crazy with spaghetti coding although DP was implemented to the tee.
    Another example of misconception is that DP proponents always carry banners of decoupling and modularization. Be very skeptical when someone gives you this shpeal. Modularization is easy to conceal for "propaganda" purposes and it is comfortable not to think about when DPs are used (especially MVC concept). Since this is just a concept - there are no real checks and balances.
    Decoupling, on the other hand, is not that easy to shove down someone's throat. Decoupling can be actually calculated - this is where a lot of idealistic beliefs that someone's code is well decoupled because of the DP fails miserably. Not because of DP itself but because of implementation. Well, sometimes pattern too.
    See, there is no black and white again.
    My point is that DPs do not protect anyone from any kind of challenges or mistakes as they don't make a better programmer. They can make one a disciplined follower but not a real creator (not that everyone must be the Creator).
    If not used properly DPs may be a ground for crappy inefficient un-scalable application as much as any other approach.
    And the last thing. I said that DPs are special suspects in Flash. This is because ActionScript and Flash are already limited frameworks that force us into thinking in MVC terms. This is just a nature of the beast. To attempt to warp it up into another MVC framework looks like a self-indulgent irrelevant academic activity to me.
    And I did not even mentioned practicalities of the target environments we develop our applications for.

  • String constructors

    I have often seen in java examples and tutorials code like:
    void method(String[] message) {
        String s = new String("Msg: " + message);
        ...and I am wondering if the following is equivalent:
    void method(String[] message) {
        String s = "Msg: " + message;
        ...Because I have the suspicion that the first syntax first creates a string (to pass as a parameter) and then the String constructor creates and returns another one. Is that true or the compiler/JVM makes sure this double work is not propagated into actual bytecode?
    Also, I am confused: what is the use of a constructor for String that takes a String as a parameter? For all the imagination that I can muster I cannot find a trickier way to waste memory, since either the parameter for the constructor is a literal string or a reference to one (and then I think that the constructor is creating an unnecessary duplicate) or the parameter is a result of some operation, like concatenation in the example above, and concatenation I suppose implicitly calls the String constructor, unless it creates strings out of thin air...
    I'm learning Java as a Foreign Language (JFL) so please you language purists pardon my clumsiness. Maybe this question was posted, answered and flamed before...

    The String constructor that takes a String parameter will always create a new String object. The compiler will never optimize that away. There are very, very few times when this will be useful, so generally it should be avoided.
    So, you might wonder why it is even around. Well, one good reason is that a String can have a reference to a character array that is much larger than the content of the String itself. The new String(String) constructor will create a String with a backing array that is only as large as it needs to be. This isn't normally a problem, but if you notice that a lot of application memory is being eaten up by unnecessarily large character arrays, then using this constructor in a few appropriate spots may fix it. However, you should never optimize code until you have profiled your application and determined that the 'problem' you are trying to fix is what is actually causing problems.

  • Object Constructors

    Well, I heard this from my "Object Oriented Programming, Distributed Computing, and Web Services" teacher:
    A constructor cannot call any method on it's code. Of course you can code-it to call te method, but it would be bad OO programming. Is that true? If so... ALL JAVA OBJECT CONSTRCUTORS WORK THAT WAY
    ( java.util.LinkedList.LinkedList(java.util.Collection clct),
    java.util.StrinkTokenizer.StringTokenizer(java.util.String str),
    java.lang.Integer(int value), as some examples...) ???
    THNX

    mm.. I but I'm not talking about invoking methods like
    utilities or something, but 2initializer methods".. I
    dunno, but I wrote the LinkedList(Collections cl)
    example.. how does the constructor works... would it
    be possible it calls a method who parses the
    collection to a LinkedList, or in any other example, I
    hava a Traingle Class with a constructor which
    receives 3 int arguments one for each side, for
    example you give negative parameters, or arguments
    which cannot create a real Triangle (they dissmatch
    when drawing it, for example) could you call a
    validation method?? or just create it?? Yes it's perfectly fine to create a method to be called by the constructor. Often it's the only good design choice.
    As mentioned above, you should avoid calling non-final, non-private, non-static methods from the constructor of a class. You can't be sure what the method will do or whether it will execute successfully. There is more to this issue than just that but if you find that you need to call an abstract or non-final method from a constructor, you consider refactoring the class using a Factory method or the AbstractFactory pattern.
    But there should be no major problems calling private or final or static methods.

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

  • Help needed - beginner Java programmer using SUN JDK1.5.0

    I have three intacting classes called CalculatorInterface.java which calls methods in Client.java and Account.java.
    CalculatorInterface-->Client (arrays of objects) c[ ]-->Account (arrays of objects a[ ] linked to c[ ]
    The problem description :
    I have in CalculatorInterface.java
    public class CalculatorInterface
    // reference to class Client
    private static final int maxClients = 4;
    // constructor for client[] object array
    private static client[] c = new client[maxClients];
    private static int total,atotal;
    private static int noClients;
    etc
    etc
    public static void main (String[] args)
    parameter definitions
    code lines
    c[noClients] = new client();
    / creates a new instance of client contained in c[]
    total = noClients;
    code lines
    method calls
    noClients++; // next c[]
    termination
    } // end of Main
    CalculatorInterface Methods including
    void WhatIsLeft()
    ... code ...
    ....code...
    c[total].getAccount(atotal).setAmount_IS_Surplus(c[total].calcWeeklySurplus(salaryYrly,weeklyExpenses,isRes));
    ... code...
    The line of code returns a NullPointerException and crashes the program !!! >_<
    is not successfully calling methods in Account.java ..... ?????
    === === === === === === > AND : I have in Client.java
    public class client
    // references to object Account a[]
    private static final int maxAccounts = 3;
    private Account[] a = new Account[maxAccounts]; //? This references a[] to client
    Client Methods including
    public Account getAccount(int num)
    return a[num]; // will be num = 0 or 1 or 2
    } // end client
    === === ==== ===> AND in Account.java
    public class Account
    Account methods
    SO ..... what's the fix ?

    Hi,
    This forum is exclusively related to discussions about creator .
    You may post this thread here
    http://forum.java.sun.com/forum.jspa?forumID=31
    MJ

  • How to discard the location of forms that are invalid

    Hi I am facing a problem with the form location for different user profiles.The defect may be that if an out of bounds location is what is stored in a users profile it will use that profile location even if it is invalid. A check needs to be made to insure that the location in the user profile is valid for the position and to ignore it if it is not.Here are 2 files give 1. that sets User profile and 2. that saves user profile.
    probably should check the validity when the profile is read from the server and discard bad entries there.
    *1.Here is the code that sets the users profile.*
    public class SetUserProfile extends UIJFrame
    private JComboBox _profileNameCmb = new JComboBox();
    private UserProfile _userProfile;
    final String OK_BTN_NAME = "Ok";
    final String CANCEL_BTN_NAME = "Cancel";
    * Constructor for the SetUserProfile object
    *@param args The command line arguments
    public SetUserProfile(String[] args)
    // Invoke base class constructor to create frame, menu and toolbar
    super(args,
    "Set User Profile",
    UIJFrame.FORM_SET_USER_PROFILE,
    true,
    false,
    UIJFrame.MENU_BASIC,
    UIJFrame.TOOL_BASIC);
    try
    // Get the user profile instance
    _userProfile = UserProfile.instance();
    // Initialize the displayable components on the form.
    initialize();
    * This method sets the profileNames attribute of the SetUserProfile object
    *@param profileNames The new profileNames value
    private void setProfileNames(final String[] profileNames)
    _profileNameCmb.setModel( new DefaultComboBoxModel( profileNames ) );
    // setting the model has the side effect of resetting the
    // picklist model to null on the model property change
    _profileNameCmb.setSelectedItem(
    ( profileNames == null ||profileNames.length == 0 )
    ? null : _userProfile.getActiveProfileName());
    * This method sets the new profile name with the user profile instance.
    *@param e Description of the Parameter
    public void onOk()
    // Clear the feedback message, if any.
    getFeedbackBar().setInformationMessage( "" );
    String userId = null;
    try
    // Get the user of record.
    userId = getClientManager().getUserOfRecord();
    // Set the new profile with the UserProfile instance.
    UserProfile.instance().setActiveProfileName(
    (String)_profileNameCmb.getSelectedItem(),
    userId,
    null );
    // Close the form.
    onCancel();
    *2.There is an other file that saves the user profile.The related code is:*
    void onOk(ActionEvent e)
    try
    if(_userProfile.saveCurrentWorkspaceAs(
    (String) _profileNameCmb.getSelectedItem(),
    this)) {
    onClose();
    Edited by: sail on Jan 3, 2008 10:04 PM
    Edited by: sail on Jan 3, 2008 10:08 PM

    Hi I am facing a problem with the form location for different user profiles.The defect may be that if an out of bounds location is what is stored in a users profile it will use that profile location even if it is invalid. A check needs to be made to insure that the location in the user profile is valid for the position and to ignore it if it is not.Here are 2 files give 1. that sets User profile and 2. that saves user profile.
    probably should check the validity when the profile is read from the server and discard bad entries there.
    1.Here is the code that sets the users profile.
    public class SetUserProfile extends UIJFrame
    private JComboBox _profileNameCmb = new JComboBox();
    private UserProfile _userProfile;
    final String OK_BTN_NAME = "Ok";
    final String CANCEL_BTN_NAME = "Cancel";
    * Constructor for the SetUserProfile object
    *@param args The command line arguments
    public SetUserProfile(String[] args)
    // Invoke base class constructor to create frame, menu and toolbar
    super(args,
    "Set User Profile",
    UIJFrame.FORM_SET_USER_PROFILE,
    true,
    false,
    UIJFrame.MENU_BASIC,
    UIJFrame.TOOL_BASIC);
    try
    // Get the user profile instance
    _userProfile = UserProfile.instance();
    // Initialize the displayable components on the form.
    initialize();
    * This method sets the profileNames attribute of the SetUserProfile object
    *@param profileNames The new profileNames value
    private void setProfileNames(final String[] profileNames)
    _profileNameCmb.setModel( new DefaultComboBoxModel( profileNames ) );
    // setting the model has the side effect of resetting the
    // picklist model to null on the model property change
    _profileNameCmb.setSelectedItem(
    ( profileNames == null ||profileNames.length == 0 )
    ? null : _userProfile.getActiveProfileName());
    * This method sets the new profile name with the user profile instance.
    *@param e Description of the Parameter
    public void onOk()
    // Clear the feedback message, if any.
    getFeedbackBar().setInformationMessage( "" );
    String userId = null;
    try
    // Get the user of record.
    userId = getClientManager().getUserOfRecord();
    // Set the new profile with the UserProfile instance.
    UserProfile.instance().setActiveProfileName(
    (String)_profileNameCmb.getSelectedItem(),
    userId,
    null );
    // Close the form.
    onCancel();
    /}2.There is an other file that saves the user profile.The related code is:
    void onOk(ActionEvent e)
    try
    if(_userProfile.saveCurrentWorkspaceAs(
    (String) _profileNameCmb.getSelectedItem(),
    this)) {
    onClose();
    }

  • My B+Tree can compile but have runtime error ... i can't tink why ...

    Sorry to bother anyone ... i have spent almost 3 weeks trying to debug the problem...
    My B+ Tree can compile but can't run as it throw invalid Null pointer Exception ..
    I suspected the error is in the split (int order ) method in the BTreeNode class but i can't remedy for it
    This my program code
    public class BTree {
    * The order of the B-Tree. All nodes of the B-Tree can store up to 2*order key values.
    private int order;
    * The number of key (with associated data values) stored in the B-Tree.
    private int count;
    * The root node of the B-Tree
    private BTreeNode root;
    * The first leaf node in the B-Tree. This field is used to give the starting point for sequential
    * access to the keys and data stored in the leaf nodes.
    private BTreeNode first;
    * The last leaf node in the B-Tree. This field is used to give the starting point for reverse
    * sequential access to the keys and data stored in the leaf nodes.
    private BTreeNode last;
    * A change count that can be used to invalidate iterators. This field is updated whenever a key plus data pair
    * is added to the B-Tree (or the data associated with a key is changed), or when a key plus data pair are
    * deleted from the B-Tree.
    private int changeCount = 0;
    // WHEN DOING ASSIGNMENT 5, DO NOT ADD ANY ADDITIONAL FIELDS TO THIS CLASS
    // You will loose marks if you add additional fields to this class. The fields above are all that
    // you need. If you need a variable in a method, use a local variable. I have seen too many
    // assignments where students add fields rather than create local variables. Hopefull the threat
    // of loosing (quite a few) marks will help reduce this habit.
    * A general exception class for errors when constructing or manipulating a B-Tree. Use the string
    * parameter to the constructor to say what the error really is.
    public class BTreeError extends RuntimeException {
    public BTreeError(String reason) {
    super(reason);
    * A constructor that creates an empty B-Tree of the given order.
    * <p/>This is the only constructor provided at the moment for this BTree class. Could consider
    * adding the equivalent of a 'copy constructor' that creates a new BTree object from an existing
    * BTree object.Constructor
    * creates the root of a btree
    * A constructor that creates an empty B-Tree of the given order.
    * <p/>This constructor need to copy the order parameter to the field of same name, and initialise the
    * root, cound, first and last fields of the BTree object.
    * @param order The order of the BTree.
    public BTree(int order) {
    count = 0;
    this.order = order;
    root = new BTreeNode(true, null, -1, null, null);
    first = root;
    last = root;
    * A method to return a SequentialIterator object that is positioned just before the first key
    * of the BTree object.
    * <p/>Do not modify this method.
    * @return A SequentialIterator object.
    public SequentialIterator iterator() {
    return new BTreeIterator();
    * A mehtod to return a SequentialIterator object that is positioned at a key found through a call
    * to the searchFor() method.
    * <p/>Do not modify this method.
    * @param position A SearchPosition() object that usually has been returne by a call to the searchFor() method.
    * @return A SequentialIterator object initialised to start at particular key in the BTree.
    public SequentialIterator iterator(SearchPosition position) {
    return new BTreeIterator(position);
    * A method to return a string representationo the BTree.
    * <p>The format of the string is:
    * <pre>BTree: Order=<digits>, size=<digits>, root=<BTreeNode string></pre>
    * <p/>Do not modify this method.
    * @return A string to represent the BTree
    public String toString() {
    StringBuffer s = new StringBuffer("BTree: Order=");
    s.append(order).append(", size=").append(size()).append(", root=").append(root.toString());
    return s.toString();
    * Method to determine the number of records stored in the B-Treee.
    * <p/>Do not modify this method
    * @return the number of records in the B-Tree.
    public int size() {
    return count;
    * method to return the order of the B-Tree.
    * <p/>
    * <p>This is the smallest number of key values for all nodes
    * except the root node. The maximum number of key values in a node is 2*order, and the maximum number
    * of child nodes for a node is 2*order+1.
    * <p/>Do not modify this method.
    * @return The order of the B-tree.
    public int order() {
    return order;
    * Insert a key plus data value into the BTree.
    * <p/>This method needs to locate the leaf node in which the key + data value should be
    * inserted, and then call the insertLeaf() method of BTreeNode to do the insertion.
    * <p/>This method will always result in a change to the BTree, so it should increment
    * the change count.
    * <p/>The method may result in only the data associated with an existing ke being changed,
    * so incrementing the count field should be done in the BTreeNode method (if needed).
    * <p/>This is one of the method you need to complete for assignment 5.
    * @param key The key associated with the data value to be added to the B-Tree
    * @param data The data value to be added (with it's associated key) to the B-Tree.
    public void add(Comparable key, Object data) {
    // you need to add the code for this method
    // i added
    BTreeNode btNode = root;
    while (!btNode.isLeaf) {
    int i=0;
    while(key.compareTo(btNode.keys) > 0) {
    i++;
    if (i == btNode.numberOfKeys) break;
    btNode = btNode.childNodes[i];
    btNode.insert(key,data);
    if (root.numberOfKeys == order*2-1) root.split(order);
    * insert a object with the given key into the tree
    //KeyNode keyNode = new KeyNode(key, data);
    // BTreeNode keyNode = new BTreeNode(key,data);
    BTreeNode btNode = root;
    while (!btNode.isLeaf) {
    int i=0;
    while(key.compareTo(btNode.key(i)) > 0) {
    i++;
    if (i == btNode.numberOfKeys())
    break;
    btNode = btNode.child(i); }
    System.out.println("hmm1");
    btNode.insert(key,data );
    System.out.println("hmm2");
    if (root.numberOfKeys == order*2-1)
    System.out.println("hmm3");
    root.split(order);
    System.out.println("hmm4");
    * This method searches the B-Tree for an occurence of the key in a leaf node and returns the result
    * of the search in a SearchPosition object.
    * <p/>Note that the key may occur in an interior node of the BTree without occuring in the leaf
    * nodes. This can be the result of a deletion operation. This method need to search down to the
    * leaf node that should contain the key if the key and associated data is in the B-Tree, and then
    * scan through the keys in the leaf node for the search key.
    * <p/>The result of the search is returned as a SearchPosition object, as this allow the return
    * of the success or failure of the search, as well as the data belonging to the key. It also
    * allows position information to be returned so that an interator can be initialised with the
    * key as the starting position for subsequent sequential access to adjacent keys.
    * <p/>This is one of the method you need to implement.
    * <p/>Implementation nodes:<br>
    * You need to find the leaf node that may contain the key (same code as for add()), then
    * scan the leaf BTreeNode for the search tree. You can do this within this method, as you
    * have total access to the fields and methods of BTreeNode (as BTreeNode is an inner class
    * of BTree). If you find the key, construct and return a SearchPosition object with the appropriate
    * details of the position, otherwise construct add return a SearchPosition object that indicates the
    * search failed.
    * @param key The key to search for in the BTree
    * @return A SearchPosition object returning the data and position information for the search
    public SearchPosition searchFor(Comparable key) {
    // You need to add the code for this method. The code below simply creates a
    // SearchPosition object which indicates an unsuccessful search.
    return new SearchPosition(false, null, -1);
    * A method to delete a node from the BTree.
    * <p/>The method should return the data object that was deleted when the key plus data object pair
    * are deleted from the B-tree.
    * <p/>The method should throw a BTreeError exception (with an appropriate reason string) if the
    * key is not found in the B-tree.
    * <p/>This is a method you can implement for bonus marks in Assignment 5.
    * <p/>Implementation notes:<br>
    * The easiest way to proceed is to use searchFor() to determine if they key is in the BTree, and
    * (if it is in the B-tree) to return position information about the key. Throw an exception if the
    * key is not in the B-tree, otherwise keep a copy of the data assocaited with the key (to return),
    * then for the leaf node containing the key (a BTreeNode object), call the deleteLeafNodeKey() method,
    * passing across the leaf key index of the key (so you don't have to find it again in the leaf node).
    * After this method deletes the key, return the data you saved as the method result.
    * @param key The key to delete (along with it's associated data) from the B-tree.
    * @return The data associated with the key that was deleted.
    public Object delete(Comparable key){
    // You need to add the code for this method.
    return null;
    * The inner class BTreeNode is used to represent the nodes in the B-Tree.
    * <p/>The nodes in the BTree are of two types:
    * <ol>
    * <li>Leaf nodes that contain the keys and associated data values, stored in ascending key order.<br>
    * These leaf nodes have next and previous pointers to adjacent leaf nodes to allow an easy
    * implementation of an iterator class to provide bi-directional sequential access to the keys stored
    * in the BTree nodes.
    * <li>Interior nodes that contain keys and links to child nodes (that are either all internal nodes
    * or all leaf nodes), organised as the node of a multi-way search tree. The interior nodes have
    * one more child node link than keys. The child node link at index k is to a node with keys that
    * are all less than the key at index k in this node. The link at index k+1 is to a child node
    * with keys that are all greater than or equal to the key at index k.
    * </ol>
    * The BTreeNode class allows you to create these two 'types' of nodes, depending on the parameters
    * passed to the constructor.
    * <p/>There are methods that should only be called for leaf nodes and methods that should only be
    * called for interior nodes. These methods should throw an exception if called by the wrong node
    * type. This class should really be designed using inheritance to mimic the pascal/C++ variant
    * record structure, but this design is relatively easy to understand and to implement.
    * <p/>Note that this class is an inner class of BTree, and so all objects will have an implict
    * reference to the BTree container object. This class has direct access to all the fields of the
    * BTree contaner object. In particular, the order of the BTree is available, hence this class
    * does not need to keep a copy of the order as a field.
    * <p/>Skeleton class provided for Objects and Algorithms Assignment 5
    * <p/>Only modify the methods where the JavaDoc indicates that you need to provide code.
    * @author a.sobey
    * @version 1.0
    * Date: 16/05/2005
    public class BTreeNode {
    * The actual number of key values stored in the BTreeNode. <br>Note that the BTree node has an implicit
    * reference to the containing BTree object, and the maximum number of nodes that can be stored in a
    * a BTreeNode (except temporarily during the split operation) is twice the <i>order</i> of the BTree.<br>
    * This field is valid for both internal and leaf nodes.
    private int numberOfKeys = 0;
    * The array of pointers to child nodes of this node. Only <i>(numberOfKeys+1)</i> are valid if <i>numberOfKeys</i>
    * is non-zero.<br>
    * This array is only valid and created for internal nodes - this array is not created for leaf nodes.<br>
    * There is space in the array created for one additional child node link - this makes the coding for
    * splitting of an internal node easier to implement.
    private BTreeNode[] childNodes;
    * A reference to the parent node of this node.<br>
    * This link is null if this node is the root node of the tree of BTreeNodes.<br>
    * This node is valid for both internal and leaf nodes.
    private BTreeNode parent;
    * The index in the parent node's array of links (the <i>childNodes</i> array) for the link to this node.<br>
    * This value should be set to -1 if this node is the root node (and so has no parent node).<br>
    * This field is valid for both internal and leaf nodes.
    private int parentIndex;
    * A link to the next leaf node in the B-tree, provided to allow easy sequential access of the keys
    * and values stored in the B-tree.<br>
    * This field is only valid if the node is a leaf node. For non-leaf nodes set the value to null.<br>
    * For leaf nodes, set the value to null if this node is the last leaf node in the B-tree.
    private BTreeNode next;
    * The link to the previous leaf node in the B-tree, provided ot allow easy reverse sequential access of the keys
    * and values stored in the B-Tree.<br>
    * This values should be set to null if this node is a leaf node but is the first leaf node in the B-Tree, or
    * if this node is not a leaf node.<br>
    * This field is only used in leaf nodes.
    private BTreeNode previous;
    * An array of comparable key objects that are stored in this node of the B-tree.<br>
    * Only the first <i>numberOfKey</i> values in the array are valid.<br>
    * The maximum number of keys in a node is 2*<i>order</i>, however there is space in this array
    * for one additional value to make the coding of the node splitting operation easier to implement.<br>
    * This field is valid for both internal and leaf nodes.
    private Comparable[] keys;
    * An array of data values associated with the keys stored in this leaf node of the B-tree.<br>
    * Only the first <i>numberOfKey</i> values are valid.<br>
    * The maximum number of data values in a node is 2*<i>order</i>, however there is space in this array
    * for one additional value to make the codingof the leaf node splitting operation easier to implement.<br>
    * This field is only valid for leaf nodes - for interior nodes this array is not created.
    private Object[] data;
    * A boolean value to indicate if the node is a leaf node or not. The structure of the remainder of the node
    * depends on this value (would be nice to have variant records in Java ...).<br>
    * This field is valid for both leaf and internal nodes.
    private boolean isLeaf;
    private int order;
    * The constructor for a BTreeNode.
    * <p/>The code for the constructor is provided - do not modify this constructor.
    * @param isLeaf True if this node is a leaf node.
    * @param parent A link to the parent node or null if this node is the root node of the B-Tree
    * @param parentIndex The index of the link in the array of child node linkes in the parent node that points to this node.
    * @param previous A link to the previous leaf node for sequentail access, or null if not a leaf node or no previous leaf nodes.
    * @param next A link to the next leaf node for sequential access, or null if not a leaf node or the last leaf node.
    public BTreeNode(boolean isLeaf, BTreeNode parent, int parentIndex, BTreeNode previous, BTreeNode next) {
    this.parent = parent;
    this.parentIndex = parentIndex;
    this.previous = previous;
    this.next = next;
    this.isLeaf = isLeaf;
    if (isLeaf)
    data = new Object[2 * order + 1];
    else
    childNodes = new BTreeNode[2 * order + 2];
    keys = new Comparable[2 * order + 1];
    public BTreeNode( int order, BTreeNode parent)
    this.order = order;
    this.parent=parent;
    this.keys = new Comparable[2*order-1];
    this.data = new Object[2*order-1];
    this.childNodes=new BTreeNode[2*order];
    this.isLeaf=true;
    * Returns the number of keys in this BTreeNode. Note that within the code in BTree you have access
    * to all the fields of BTreeNode, so this method is not strictly necessary.
    * @return The number of keys in this BTreeNode object.
    public int numberOfKeys() {
    return numberOfKeys;
    * Returns the container BTree object for this BTreeNode object. You may like to check that container objects
    * are the same when manipulating two BTreeNode objects.
    * @return the containing BTree object.
    public BTree container() {
    return BTree.this;
    * A private method to return a string representation of the array <i>keys</i>. This method is used in
    * the toString() method for this class.<br>
    * Do not modify the code provided for this method.
    * @return A string representation of this nodes array of keys.
    private String keyString() {
    StringBuffer s = new StringBuffer("{");
    for (int index = 0; index < numberOfKeys; index++)
    s.append(index > 0 ? "," + keys[index] : keys[index]);
    return s.append("}").toString();
    * A private method to return a string representation of the array of data values stored in a leaf node.<br>
    * This method is used in the toString() method of BTreeNode. The method does not check if this node is a
    * leaf node, as it is not intended to be called directly from outside of this class, and the toString()
    * method only calls this method if the node is a leaf node.<br>
    * Do not modify the provided code for this method.
    * @return a string representation of the data values array of a BTreeNode.
    private String dataString() {
    StringBuffer s = new StringBuffer("(");
    for (int index = 0; index < numberOfKeys; index++)
    s.append(index > 0 ? "," + data[index] : data[index]);
    return s.append(")").toString();
    * A private method to return a string prepresentation of the array of child node links in an interior node.<br>
    * This method is used in the toString() method. This method does not check if this node is an interior
    * node, so you must take care to only call this method for interior nodes.<br>
    * Do not modify the provided code for this method.
    * @return A string representation of the array of child nodes of this BTreeNode.
    private String childString() {
    StringBuffer s = new StringBuffer("<");
    for (int index = 0; index < numberOfKeys + 1; index++)
    s.append(childNodes[index] + (index == numberOfKeys ? "" : ","));
    return s.append(">").toString();
    * The toString method provides a string representation of a BTreeNode.<br> This particular method does not
    * include the details of all the fields of a BTreeNode. While debugging your code, you may like to include
    * more information (such as the parentIndex value), but in your final submission you must have the code
    * as provided in the skeleton BTreeNode class provided to you.
    * @return A string representation of a BTreeNode.
    public String toString() {
    if (isLeaf)
    return (new StringBuffer("[")).append(numberOfKeys)
    // .append(',').append(parentIndex) // uncomment this line if need to check parentIndex values
    .append(',').append(keyString()).append(',').append(dataString()).append(']').toString();
    else
    return (new StringBuffer("[")).append(numberOfKeys)
    //.append(',').append(parentIndex) // uncomment this line if need to check parentIndex values
    .append(',').append(keyString()).append(',').append(childString()).append(']').toString();
    * Returns the key with the given index in this node. Throws a BTreeError exception if the index is not valid.<br>
    * Do not modify this provided code.
    * @param index The index of the key.
    * @return The key value at the given index.
    public Comparable key(int index) {
    if (index < 0 || index >= numberOfKeys)
    throw new BTreeError("Key index out of range - value = " + index);
    return keys[index];
    * Returns the child node at the provided index into the childNodes array.<br>
    * A BTreeError exception is thrown if the node is not an internal
    * node or if the index is not valid.
    * <p/>Note that the child node returned will have keys that are all less than the key stored
    * in the <i>keys</i> array of this node at the given index value (except the last childNode
    * at index numberOfkeys, as this node has keys that are all greater than or equal to the last
    * key value stored in this node).<br>
    * Do not modify the provided code for this method.
    * @param index The index into the array of child nodes for this internal BTreeNode object.
    * @return The child node link.
    public BTreeNode child(int index) {
    if (isLeaf) throw new BTreeError("child() called for a leaf node");
    if (index < 0 || index > numberOfKeys)
    throw new BTreeError("Child node index out of range - value = " + index);
    return childNodes[index];
    * Returns the data value associated with the key at the given index. An BTreeError exception is thrown if the
    * node is not a leaf node or if the index is invalid.
    * <p/>Do not modify the provided code for this method.
    * @param index The index of the key assocaited with the data value.
    * @return The data value associated with the key with given index.
    public Object data(int index) {
    if (!isLeaf) throw new BTreeError("data() called for an internal node");
    if (index < 0 || index >= numberOfKeys)
    throw new BTreeError("Data index out of range - value = " + index);
    return data[index];
    * This method is used to determine if this node is a leaf node.
    * @return True if this node is a leaf node.
    public boolean isLeaf() {
    return isLeaf;
    * Inserts the (key, data) pair into this BTreeNode object.
    * <p/>You must supply the code for this method.
    * <p/>Implementation notes:<br>
    * <ol>
    * <li>Throw an exception if this node is not a leaf node.
    * <li>Scan the keys array for index of the key greater than or equal to the insertion key.
    * <li>If the key at the index is equal to the insertion key, update the data field and return - you are done.
    * <li>Otherwise shuffle the keys values from the insertion index along to make a hole for the insertion key,
    * and insert the insertion key into the keys array. Do the same for the data array values to insert the
    * new data value into the data array at the insertion index.
    * <li>increment the number of keys, and increment the container BTree object's count field.
    * <li>If the number of keys in the node is now no more than 2*order, you are done, so simply return.
    * <li>Otherwise the node has (2*order+1) key values, and need to split. The split operation leaves the first
    * <i>order</i> keys and data values in this node (and so the node's numberOfKeys value will become
    * <i>order</i>, and moves the remaining (order + 1) keys and data values to a new BTreeNode leaf node
    * that you need to create.<br>
    * You need to fix up the previous and next fields of this leaf node and the new leaf node you have created.<br>
    * Two sub-cases:
    * <ol>
    * <li>If this node is the root node (i.e., it does not have a parent node), the split of this node will create
    * a new root node, with a single key (the key at index (order+1)) and this node and the new BTreeNode as
    * the child nodes. In my solution I used a call to the method newRootNode to do this. The newRootNode()
    * method will also be used when a split of an interior node creates a new root node. See the JavaDoc for
    * details of what the newRootNode() method should do. Once the new root node has been created, and all
    * the fields updated due to the split, you are done.
    * <li>Otherwise we need to insert in this node's parent node the middle key (at index (order+1) and the
    * new node that we created. This is done by the method insertInterior(). The method is passed the
    * key to insert (at location this.parentIndex in the keys array of the parent node), the index to
    * to insert the key (this.parentIndex), and the new leaf node (that will be inserted at index
    * (this.parentIndex+1) in the parent node's child links array).
    * </ol>
    * </ol>
    * @param key The key to insert into the leaf node.
    * @param data The key's corresponding data value.
    public void insertLeaf(Comparable key, Object data) {
    // You need to provide the code for this method.
    // BTreeNode temp = new
    int size = this.data.length;
    int counter = 0;
    this.keys[size] = key;
    this.data[size] = data;
    sort(size);
    public int compareTo(Comparable o2) {
    // Integer o1 = (Integer) o2;
    return (((Integer)o2).compareTo(this));
    *split()
    *Splits a node into to nodes. This can only be done, if the node is full
    *The midlest key go up into the parent, the left ones of them rest in
    *this node, and the right ones go into a new node.
    private BTreeNode split(int order) {
    if (numberOfKeys == order*2-1) {
    BTreeNode right = null;
    if (parent == null) { // algo for the root-node
    BTreeNode left = new BTreeNode(order, this);
    right = new BTreeNode(order, this);
    for (int i=0; i<order-1; i++) {
    left.keys[i] = keys[i];
    left.data[i] = data[i];
    right.keys[i] = keys[order+i];
    right.data[i] = data[order+i];
    if (!isLeaf()) {
    for (int i=0; i<order; i++) {
    left.childNodes[i] = childNodes[i];
    left.childNodes[i].parent = left;
    right.childNodes[i] = childNodes[order+i];
    right.childNodes[i].parent = right;
    left.isLeaf = false;
    right.isLeaf = false;
    } else isLeaf = false;
    keys[0] = keys[order-1];
    numberOfKeys = 1;
    left.numberOfKeys = order-1;
    right.numberOfKeys = order-1;
    for (int i=1; i<order*2-1; i++) {
    keys[i] = null;
    data[i] = null;
    childNodes[i+1] = null;
    childNodes[0] = left;
    childNodes[1] = right;

    * Don't post that much code. There should never be a reason to. You should be able to break your code down into small enough pieces that you can post a small example that demonstrates your problem.
    * When you do post code, use [code] and [/code] tags to make it readable. You can use the code button on the message entry page.
    * The stack trace will tell you which line the NPE occurred on, where it was called from, where that was called from, etc. You can use that to help you find your error. Look at the line it's complaining about. What references are on that line followed by a dot, and what arrays do you try to access the elements of. One of those must be null.
    * Now that you know what[b] is null, put in a bunch of print statements to track [b]how it got to be null.

Maybe you are looking for

  • Report to get total number of users logged in after a certain date

    Hi, Is there any report available in SIM which can give us the record of the users who logged into it after a certain date. I tried to use Historical User Changes Report but in this report there is an mandotory aatribute 'object Type' which filters t

  • Trouble Cleaning Up At The End of an Automator Action

    So my automator action currently downloads a file (a .dmg), mounts it, copies its contents to Applications, and then... I then want to unmount the dmg and throw the dmg away. However, by this point I no longer have the references to these two items:

  • Barcodes in CR's

    Post Author: lmbap CA Forum: Charts and Graphs Hello, I', using CR XI Developper Edition and I would like to know if there are any tool to implement so I can have barcodes in my (web)reports.Now our client is using labels to tag the reports and the f

  • IPhoto 08 fails to detect my Canon SD800 IS

    I have a Intel iMac (the aluminum one) running Mac OSX 10.5.2. For some reason, my iMac is having a difficult time seeing my digital camera (Canon SD800 IS). Does anyone else have this problem? If so, how does one get around it?

  • Copy entity between EntityManagers - Exception TOPLINK-7251

    I am trying to copy rows from one database to another using Toplink. The tables have a composite primary key. Sample.java copies over three thousand rows successfully before an exception. h3. Configuration         <persistence-unit name="STLMOSQL">