Deep Copy for an array of strings - deep-copy

I need to demonstrate a code which implements deep copy for an array of strings in JAVA . Following is the code I developed.Anybody can confirm if it is correct or not?
public class Paper implements Cloneable{
private String Type ;
private String[] Text ;
//Default constructor to initialize variables.
public Paper()
{
this.Type="" ;
this.Text = new String[0] ;
}
//Necessary constructor.
public Paper(String Type, String[] Text)
{
this.Type= Type;
//Deep copy
this.Text = new String[Text.length] ;
this.Text = Text.clone() ;
//Flat Copy
this.Text = Text ;
}
//Here we implements the interface "Cloneable" to make deep copy when we want to
//extend an array of Paper objects.
public Object clone()
{
try
{
Paper cloned = (Paper) super.clone();
cloned.Text = (String[])Text.clone();
return cloned;
}
catch(CloneNotSupportedException e)
{
return null;
}
}

Related

Windows Forms Custom DataGridView

I am not very experienced with Windows Forms and am not pretty sure how I should tackle with this task the best way possible. I have a class which looks like this:
public class VariableMapping
{
private string variableName;
private string variableText;
private string variableSelector;
public VariableMapping(string variableName, string variableText, string variableSelector)
{
this.VariableName = variableName;
this.VariableText = variableText;
this.VariableSelector = variableSelector;
}
public string VariableName
{
get { return this.variableName; }
set { this.variableName = value; }
}
public string VariableText
{
get { return this.variableText; }
set { this.variableText = value; }
}
public string VariableSelector
{
get { return this.variableSelector; }
set { this.variableSelector = value; }
}
}
I want to create a DataGridView which should be bound to a number of elements of type VariableMapping in a list. However, I want only 1 of the properties(VariableText) of every instance to be shown in the DataGridView but I want to be able to address the whole object through the DataGrid when I need to. I also need to add 2 more custom columns: a ComboBox with predefined values and a NumberBox.
It might seem a really simple task but I'm trully unexperienced in WinForms and couldn't find a solution I can use already. Thank you!
Edit: I am trying something like this but it doesn't seem to work properly:
public partial class MappingTable : Form
{
private DataGridView dataGridView1 = new DataGridView();
public MappingTable(List<VariableMapping> variableMappings)
{
InitializeComponent();
var colors = new List<string>() { "#color_k1", "#color_k2", "#color_s1" };
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AutoSize = true;
dataGridView1.DataSource = variableMappings;
DataGridViewColumn titleColumn = new DataGridViewColumn();
titleColumn.DataPropertyName = "VariableText";
titleColumn.HeaderText = "Variable";
titleColumn.Name = "Variable*";
dataGridView1.Columns.Add(titleColumn);
DataGridViewComboBoxColumn colorsColumn = new DataGridViewComboBoxColumn();
colorsColumn.DataSource = colors;
colorsColumn.HeaderText = "Color";
dataGridView1.Columns.Add(colorsColumn);
DataGridViewTextBoxColumn opacityColumn = new DataGridViewTextBoxColumn();
opacityColumn.HeaderText = "Opacity";
dataGridView1.Columns.Add(opacityColumn);
this.Controls.Add(dataGridView1);
this.AutoSize = true;
}
}

Make a custom ArrayList toString() that displays contents line by line?

I understand with toString() methods, their must be a return type, when an external method is called.
The comment block below describes what I'm trying to do.
Later on when I work with setters and getters, this knowledge will most definitely be invaluable.
import java.util.*;
public class Display_ArrayList {
static ArrayList<String> cars = new ArrayList<String>();
public static void main(String[] args) {
cars.add("Nissan Maxima");
cars.add("Toyota Prius");
cars.add("Renault Clio");
cars.add("Ford Focus");
cars.add("Volkwagen Passat");
System.out.println("");
System.out.println("[Standard toString()]:");
System.out.println(cars.toString());
System.out.println("");
System.out.println("[Custom toString()]:");
System.out.println(custom_cars_toString());
}
// Array list displays the car list all on the same line
public static String getCarList() {
return cars.toString();
}
// *************************************************************************
// I want Array list contents to be displayed on their own lines without
// commas or brackets, while at the same allowing this method to be
// retrieved by a toString() method
// *************************************************************************
// public static void getCarList() {
// for (String element : cars)
// System.out.println(element);
// }
public static String custom_cars_toString() {
return "The cars contained are: \n" + getCarList();
}
}
Can't you just make a class that extends ArrayList which overrides the toString method? Then you could make something like this:
public class DisplayArrayList<T> extends ArrayList {
#Override
public String toString() {
String res = "";
for (int i = 0; i < size(); i++) {
res += (i == 0 ? "" : "\n") + get(i).toString();
}
return res;
}
}
Then you can just put your cars in a DisplayArrayList instead of an ArrayList and then when you print that you will get them all on individual lines.
For example this:
DisplayArrayList<String> list = new DisplayArrayList<>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
list.add("test5");
System.out.println(list);
Would output this:
test1
test2
test3
test4
test5
Sorry if this doesn't do what you want to, couldn't completely figure out what you want from your post.

nullpointerexception for array of objects

I have the following test class
public class Driver
{
public static void main(String [] args)
{
BankAccount[] b1 = {new BankAccount(200), new BankAccount(300), new BankAccount(250), new BankAccount(300), new BankAccount(200)};
BankAccountGroup bag = new BankAccountGroup(b1);
}
And BankAccountGroup:
public class BankAccountGroup
{
private BankAccount bank[];
public BankAccountGroup(BankAccount[]b)
{
for(int i =0; i<5;i++)
{
bank[i] = b[i];
}
}
these are just snippets of the whole code. Im getting a nullpointerexception for these two lines:
- bank[i] = b[i];
- BankAccountGroup bag = new BankAccountGroup(b1);
Please help
When you declare bank[] in the BankAccountGroup class it looks like you forgot to give it a length. Because of this, when you call bank[i] in your for loop, anything after i=0 is probably going to give you an error.
something like
private BankAccount[] bank = new BankAccount[5];
Either initialize your array first(Bad).
Or assign it from the value you pass the constructor.
private BankAccount[] bank;
public BankAccountGroup(BankAccount []){
bank = b;
}
You are not initializing the bank array. You also shouldn't assume that the argument will have a length of 5 elements. I would rewrite the class to something like this:
public class BankAccountGroup
{
private BankAccount bank[];
public BankAccountGroup(BankAccount[]b)
{
if (b != null)
{
bank = new BankAccount[b.length];
for(int i=0; i<b.length;i++)
{
bank[i] = b[i];
}
}
}
}

Passing checkedlistbox.checked items cast as a List<BuiltInCategory> from a Form instance to a Revit class function

I am not having any issues making calls from the form instance to the Revit class. It's when I try to assign a List to the Revit class's function categoryList(), that I get a variable doesn't exist in the context error. I tried prefixing a reference to the instance of the form class "Form UF = new Form;" This doesn't work.
//The Revit Class
public Result Execute(ExternalCommandData commandData, ref string message,....)
{
User_Form UF = new User_Form(commandData);
UF.ShowDialog();
public List<BuiltInCategory> categoryList(Document doc, int intSwitch)
{
//list built in categories for built in filter_1
builtInCats_List = new List<BuiltInCategory>();
switch (intSwitch)
{
case (1):
...
case (3):
...
case (4):
{
builtInCats_List = newStateCb1;
return builtInCats_List;
}
default:
{
builtInCats_List = newStateCb1;
return builtInCats_List;
}
}
}
using Form = System.Windows.Forms.Form;
using WS = ModelAuditor_2014.WorksetSorter_2014;
using ModelAuditor_2014;
using System.Threading;
//The Form
namespace ModelAuditor_2014
{
public partial class User_Form : Form
{
//Constructor
WorksetSorter_2014 WS = new WorksetSorter_2014();
//Revit references
public Autodesk.Revit.UI.UIApplication rvtUiApp;
public Autodesk.Revit.UI.UIDocument rvtUiDoc;
public Autodesk.Revit.ApplicationServices.Application rvtApp;
//Global Variables
public List<BuiltInCategory> Filter01_CategoryList;
public List<BuiltInCategory> Filter02_CategoryList;
public int intSwitch;
public List<BuiltInCategory> newStateCb1;
public User_Form(ExternalCommandData commandData)
{
//Revit references
rvtUiApp = commandData.Application;
rvtUiDoc = rvtUiApp.ActiveUIDocument;
rvtApp = rvtUiApp.Application;
InitializeComponent();
}
public void User_Form_Load(object sender, EventArgs e)
{
//use rvtDoc = Doc
Autodesk.Revit.DB.Document rvtDoc = .....
//CheckedListBox for filter01
checkedListBox1.DataSource = WS.categoryList(rvtDoc, intSwitch = 1);
Filter01_CategoryList = new List<BuiltInCategory>();
Filter01_CategoryList = WS.RetrieveSchema(rvtDoc, false);
foreach (BuiltInCategory ChkedB1 in Filter01_CategoryList)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.Items[i].ToString() == ChkedB1.ToString())
{
checkedListBox1.SetItemChecked(i, true);
}
}
}
public List<BuiltInCategory> returnNewStateCB1()
{
newStateCb1 = checkedListBox1.CheckedItems.Cast
<BuiltInCategory>().ToList<BuiltInCategory>();
return newStateCb1;
}
I passed the list from the win form to another public function in the revit app, I was able to access the list returned by this function.

Finding objects index in a multidimensional array

Im making an inventory and Im adding stacks but ive hit an issue
below is what I want compared to what works
I just want to find the index of the object I pass through
myArray[0] = [item:object,StackAmmount:int]
var myArray:Array = new Array();
myArray[0] = ["name1",1];
myArray[1] = ["name2",1];
myArray[2] = ["name3",1];
trace("Name" , myArray[0][0]);
//traces "name1"
trace("Stack" , myArray[0][1]);
//traces "1"
trace("Index of Object" , myArray.indexOf("name2"));
//traces -1
// Not Working (NOT FOUND)
//How can I find the index of "item1" or "item2" in the above example
var myOtherArray:Array = new Array();
myOtherArray[0] = "name1";
myOtherArray[1] = "name2";
myOtherArray[2] = "name3";
trace("Name" , myOtherArray[0]);
//traces "name1"
trace("Index of Object" , myOtherArray.indexOf("name2"));
//traces 1
//Working
perhaps there is a better way of dealing with stacks?
Paste Bin Link: http://pastebin.com/CQZWFmST
I would use a custom class, therefore a 1D vector would be enough. The class would contain the name of the item, and the stack. You could subclass this class to override the maxStack variable of the item, and then the searches would be easier aswell, you could just iterate through the vector and check the name.
public class InventoryItem
{
protected var _name:String;
protected var _stack:int;
protected var _maxStack:int;
public function InventoryItem():void {
}
public function get name():String {
return _name;
}
public function get stack():int {
return _stack;
}
public function set stack(value:int):void {
_stack = value;
}
public function get maxStack():int {
return _maxStack;
}
}
...
public class InventoryWeapon extends InventoryItem
{
public function InventoryWeapon(__name:String, startStack:int) {
_maxStack = 64;
_name = __name;
_stack = startStack;
}
}

Resources